Inside the function you are assigning the new memory allocated by malloc to dArray
, which has block scope. You need to pass this pointer back to the calling function. dArray
is a copy of the pointer that you passed in, and when you return to the calling function, the original pointer is unchanged. You should have a function call like:
ptr = ChangeDynamicArraySize(ptr, oldSize, newSize);
Since dArray
is a copy of the pointer passed in the function call, when you change the value of *dArray
, THAT is visible outside of the function because you are changing the value stored at the memory location pointed to by both the original pointer and the copy. But when you reassign the dArray
pointer inside the function, you are just saying that this pointer should now point to some other location. The original still points to the original location.
The solution in the original question suffers from a fundamental problem: when you pass a pointer to a section of memory to a function, and the pointer reallocates that memory using malloc()
or calloc()
or realloc()
, the new memory has a new address. This is true even with realloc()
because there might not be enough contiguous bytes at the old location to allocate the requested memory. The original solution reallocates memory inside of the ChangeDynamicArraySize()
function, and then modifies the contents of this memory. But after returning, the calling function has no idea where the new memory is. So, you have to return a pointer to the newly allocated memory to the caller.
@Diti proposed an alternate solution to get around this by passing the address of the pointer to the first element of the array. This pointer can be dereferenced and given the value of the address of the newly allocated memory. In this way, the calling function is none the wiser, because whenever the calling function accesses the array, it does so through the pointer that provides the address of the first element of the array. Neat. But I still think I prefer to explicitly pass the pointers whenever possible-- it seems clearer to me.