+ 1
I Don’t Understand
I don’t understand how this code outputs a value of 1: int * test() { static int x[4]; for(int i=0; i<4; i++){ x[i] = i%2; } return x; } int main(){ int * arr=test(); printf(“%d”, *(arr+3)); } Is *(arr+3) summing up the first 3 elements of the array or is it pointing to the first element of the array and adding 3?
7 Respostas
+ 4
(Not so) Short supplement: This behaviour is also the reason why you usually pass the array size along with an array when passing it to a function. Since the array is really just a pointer, the compiler can not know to how many consecutive elements it should be pointing, as before and after the allocated block of memory, there are just other memory cells, which you can also access by simply going far enough with the pointer arithmetic (and thanks to the fact C doesn't give a damn and doesn't check if you are accessing an array out of bounds). You can also access the elements right before the array with a call like
*( arr - 1 ),
which will return the element stored in memory right before your array, but all of this is undefined behaviour anyway.
The result of attempting such things might range from everything going according to plan to the program crashing over to everything being on fire.
+ 3
Neither, actually.
Have a look at the return type of your function. It returns a pointer, not an array. The reason is that an array is nothing more than a pointer to a continuous block of memory. Using the name of an array is equivalent to using a pointer to the first element inside the array.
Furthermore, accessing an array is pointer-based too. A call like
arr[ 3 ]
is behind the hood transformed into
*( arr + 3 ).
What happens here is the pointer 'arr' is first advanced three times and then dereferenced. Since it usually points to the first element of the sequence, it now points to the third element behind the first - the fourth element, before being dereferenced.
It might be confusing at first, but the important thing to remember is that an array is a pointer to a continuous block of memory, everything else is pointer arithmetic (you can look it up for more information on the topic).
+ 1
Oh ok, so arr[3] = *(arr+3), am i understanding that correctly?
+ 1
Yes, exactly.
+ 1
That helps a lot! Thank you!