If I have an int array:
int *array;
array = malloc(5 * sizeof(int));
and I malloc to it as above, I can then access it and set values to it. Everything is fine.
But if I create that int pointer and pass to it a function and malloc inside the function, I can't access/set values to the array unless I pass it to the array as a pointer to a pointer?
some_void_function(int *array) {
array = malloc(5 * sizeof(int))
}
int *array;
some_void_function(array);
*(array + 3) = 5; // DOES NOT WORK
To fix it I can make the array accept (int **array) as a parameter and pass in the address of the pointer (so a pointer to a pointer), dereference it, and assign it with malloc:
some_void_function(int **array) {
*array = malloc(5 * sizeof(int))
}
int *array;
some_void_function(&array);
*(array + 3) = 5; // WORKS
Could someone explain this to me? Am I not doing the same thing in both situations? Pass the address and then just dereferencing it is the same thing as just pass in the single pointer in the first place right?