Reputation: 1084
Hey I was experimenting a bit with C/C++ and pointers while reading stuff here
I made myself a function to return a pointer to the int at some place in a global array.
int vals[] = { 5, 1, 45 };
int * setValue(int k) {
return &vals[k];
}
However I was able to do this
int* j = setValue(0);
j++;
*j = 7;
to manipulate the array
but that:
*(++setValue(0)) = 42;
din't work.
Notice however *setValue(0) = 42;
works
From what I understand I call the function and get some pointer I increment it to make it point to the 2nd element in my array. Lastly I deference the pointer and assign a new value to the integer it pointed to.
I find C++ pointers and references can be somewhat confusing but maybe someone can explain me this behavior.
EDIT: This question is NOT a duplicate of Increment, preincrement and postincrement
because it is not about pre- vs. post-increment but rather about increment on pointers that are the return of a function.
EDIT2:
Tweaking the function
int ** setValue(int k) {
int* x = &vals[k];
return &x;
}
You can use
*(++(*setValue(1))) = 42;
Upvotes: 3
Views: 807
Reputation: 4366
You can't call a unary operator (++
) on something that is not a variable. setValue(0)
is treated as a value.
So,
*(setValue(0)++) = 42;
should be
*(setValue(0) + 1) = 42;
Upvotes: 5