Reputation: 789
I have a homework assignment to figure out what this will print out:
static const int *f(const int a[], int i) { return &a[i + 2]; }
int a[] = { 1, 2, 3, 4, 5, 6, 7 };
f(a, 1)[1]; //What this will return
I ran the program and got 5, but do not understand, in the least, how this works.
The function f looks like a pointer to me, but I don't understand what the subscript 1 is doing.
Could someone explain this to me, in depth?
Upvotes: 0
Views: 80
Reputation: 2918
first we have the regular array
a[] = 1 , 2 , 3 , 4 , 5 , 6 , 7
original index = 0 , 1 , 2 , 3 , 4 , 5 , 6
when the call to f(a,1)
happens, the pointed element is
f(a,1) ↓
a[3] = 1 , 2 , 3 , 4 , 5 , 6 , 7
original index = 0 , 1 , 2 , 3 , 4 , 5 , 6
then the address is return with &
. &a[3]
is the address of a[3]
, so the it return the address of the number, as and is treated like an array, that starts in that exact address.
f(a,1) = 1 , 2 , 3 , 4 , 5 , 6 , 7
new index = -3 , -2 , -1 , 0 , 1 , 2 , 3
when f(a,1)[1]
is asked, the index 0
is where the index 3
used to be.
↓
f(a,1)[1] = 1 , 2 , 3 , 4 , 5 , 6 , 7
new index = -3 , -2 , -1 , 0 , 1 , 2 , 3
and returns 5
.
Upvotes: 1
Reputation: 726479
The problem is entirely about pointer arithmetic / array indexing (which are related to each other). The function is there to throw you off.
The function returns the address of the array's element at index i + 2
. You pass 1
for i
, so you're getting back the address of the fourth element (recall that array indexes are zero-based).
What happens next is that you use the result as a new origin of an array, and pick the second element from it. That second element happens to be 5
.
Index : 0 1 2 3 4 5 6
- - - - - - -
Value : 1 2 3 4 5 6 7
^
|
Return value of f(a, 1) is the new origin
Upvotes: 3
Reputation: 11730
It's a bit convoluted, but the function f() returns the address of the fourth element. The subscript after the function call then moves up one to the fifth element, which is the number 5.
Upvotes: 0