int * func()
{
static int array[10];
int i = 0;
while(i<10){
array[i] = i + 1;
i++;
}
return array;
}
int main()
{
int *pointerFunc;
pointerFunc = func();
for (int i = 0; i < 10; i++ ) {
printf("*(pointerFunc[%d]) : %d\n", i, *(pointerFunc + i));
}
return 0;
}
I have a function which creates an array. In main, I want to print every element from that array. I used a pointer to get "access" to my array in the function. It does work the way it is, but I don't really understand why. To be precise, I wonder what is happening here (sure it prints the studd, but the pointer thing...):
printf("*(pointerFunc[%d]) : %d\n", i, *(pointerFunc + i));
I don't quite understand this:
*(pointerFunc + i)
It works, but how and why? It does print every element of my array, but I dont't get it.
What is the pointer "seeing"?
printf("*(pointerFunc[%d]) : %d\n", i, *(pointerFunc + i));
Here, you are using pointer arithmetic to access each element of the array.
The expression *(pointerFunc + i)
adds i
to the memory address stored in pointerFunc
, and then dereferences the resulting memory address to access the value stored in that memory location. Since pointerFunc
points to the first element of the array, *(pointerFunc + i)
gives you the value stored in the i
-th element of the array.
Alternatively, you could also use the array subscript operator []
to access the elements of the array using the pointer variable, like this:
printf("pointerFunc[%d] : %d\n", i, pointerFunc[i]);
Both expressions are equivalent and will give you the value stored in the i
-th element of the array.