[英]C realloc segmentation fault
I've got a very simple piece of C code that uses malloc and realloc, but it induces a seg fault if I change a value that was part of the first array. 我有一个非常简单的C代码,它使用malloc和realloc,但是如果我更改了第一个数组的一部分的值,则会引发段错误。
#include <stdlib.h>
void increase(int** array)
{
int * new_array;
new_array = realloc(*array, 10 * sizeof(int));
if (new_array != NULL) {
*array = new_array;
}
else {
// Error in reallocation
}
int i = 3;
*array[i] = 2; // Seg fault if i = 0, 1, 2, 3
}
main()
{
int *array = malloc(4 * sizeof(int));
increase(&array);
free(array);
}
Is my understanding of pointers at fault? 我对错误指针的理解吗? Can anyone explain what's happening and how I can use realloc properly? 谁能解释正在发生的事情以及如何正确使用realloc?
Many thanks! 非常感谢!
You probably need: 您可能需要:
(*array)[i] = 2;
The [] operator binds before the *, so your version was doing *(array[i]) which is, well, wrong. []运算符在*之前绑定,因此您的版本正在执行*(array [i]),这是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.