The usage of pointer star in C
c, pointers
Solution
`temp` gets a copy of the address of `myArray`, but then you assign some `malloc`ed memory to `temp`, so the original assignment was pointless and had no lasting effect. You then modify the `malloc`ed memory, but that doesn't change `myArray` at all. To change `myArray` in `main`, you have to assign
*myArray = temp;
at the end of `FillArray`.
void FillArray(int** myArray)
{
int* temp;
temp = (int*) malloc(sizeof(int) * 2);
temp[0] = 1;
temp[1] = 2;
*myArray = temp;
}
does what you intend.
Problem
I asked the question: Pass array by reference using C. I realized my problem was the usage of the pointer star in C. And eventually it turned out that, this method works fine for my program: ``` #include <stdio.h> void FillArray(int** myArray) { *myArray = (int*) malloc(sizeof(int) * 2); (*myArray)[0] = 1; (*myArray)[1] = 2; } int main() { int* myArray = NULL; FillArray(& myArray); printf("%d", myArray[0]); return 0; } ``` Everyting was fine up to that point. Then, I modified the FillArray() function like the following for a better code readability: ``` #include <stdio.h> void FillArray(int** myArray) { int* temp = (*myArray); temp = (int*) malloc(sizeof(int) * 2); temp[0] = 1; temp[1] = 2; } int main() { int* myArray = NULL; FillArray(& myArray); printf("%d", myArray[0]); return 0; } ``` Now, I get the following run-time error at the printf line: Unhandled exception at 0x773115de in Trial.exe: 0xC0000005: Access violation reading location 0x00000000. Even though I'm not an C expert, it seemed legitimate to do this modifying. However, apparently it doesn't work. Isn't the syntax a little bit confusing? Do I miss something here? Thanks for your helpful answers, Sait.