我试图用 realloc
增加我用 malloc
创建的 **array
的大小。
我将 **array 提交给一个我想增加大小的函数。
这是增加大小的部分:
imginf->height = imginf->height * 2;
imginf->width = imginf->width * 2;
array = realloc(array, imginf->height * sizeof(d*));
for(int i = 0; i < imginf->height; i++) {
array[i] = malloc(imginf->width * sizeof(d));
}
之后,我用两个 for 循环填充数组。一切正常!
在下一个函数中,我尝试将该数组保存在文件中。这里我还使用了两个 for 循环。
在第一个 for 循环中,我遍历了高度,在这里我遇到了问题。
如果循环计数器是 (imginf->height /2)
我就用完了数组。对于宽度,一切正常。
出了什么问题?特别是,为什么我可以填充数组?
编辑
这里是保存的函数定义:
void Save(char * newname, inf imginf, d **array);
d是一个带有3个无符号字符的结构体。
这里是 realloc 函数的定义:
void reallocBig(inf *imginf, d **array);
Greetz。
Im trying to increase the size of a **array
with realloc
which I have created with malloc
.
I committed the **array
to a function where I would like to increase the size.
Here is the part which increase the size:
imginf->height = imginf->height * 2;
imginf->width = imginf->width * 2;
array = realloc(array, imginf->height * sizeof(d*));
for(int i = 0; i < imginf->height; i++) {
array[i] = malloc(imginf->width * sizeof(d));
}
After that, I fill the array with two for loops. Everything works fine!
In the next function I try to save that array in a file. Here I use also two for loops.
With the first for loop I walk through the height and here I get the problem.
If the loop counter is (imginf->height /2)
I ran out of the array. For the width everything’s works fine.
What went wrong? Especially, why could I fill the array?
Edit
Here the function definition for saving:
void Save(char * newname, inf imginf, d **array);
d is a struct with 3 unsigned chars.
Here the definition for the realloc function:
void reallocBig(inf *imginf, d **array);
Greetz.
发布评论
评论(1)
C 是一种按值传递语言。您的
reallocBig
函数无法修改调用方中数组的值。您需要将其更改为采用d ***
参数,并在函数中“填充”该指针:C FAQ 有一个 询问您的问题。您还应该注意,当前的实现泄漏了数组中以前的所有条目。
C is a pass-by-value language. Your
reallocBig
function can't modify the value of the array in the caller. You need to change it to take ad ***
parameter, and "fill in" that pointer in the function:The C FAQ has a question about precisely your problem. You should also note that your current implementation leaks all of the previous entries in the array.