I have a pretty basic question, I tried to answer it for many hours now but it still doesn't work. I want to malloc an array in main, pass it to another function, reallocate it and then change it's values. Why does the following code work:
void fun(int **array, int *size) {
*array = (int *) realloc(*array, *size * sizeof(int));
*array[0] = 1;
return;
}
int main() {
int size = 5;
int *array = (int *) malloc(2 * sizeof(int));
fun(&array, &size);
return 0;
}
... but as soon as I try to change array[1] like this:
void fun(int **array, int *size) {
*array = (int *) realloc(*array, *size * sizeof(int));
*array[0] = 1;
*array[1] = 2;
return;
}
int main() {
int size = 5;
int *array = (int *) malloc(2 * sizeof(int));
fun(&array, &size);
return 0;
}
... it doesn't work anymore. It gives me segmentation fault and invalid write of size 4.