c++ - Increment pointer returned by function -
hey experimenting bit c/c++ , pointers while reading stuff here
i made myself function return pointer int @ place in global array.
int vals[] = { 5, 1, 45 }; int * setvalue(int k) { return &vals[k]; }
however able this
int* j = setvalue(0); j++; *j = 7;
to manipulate array
but that:
*(++setvalue(0)) = 42;
din't work. notice *setvalue(0) = 42;
works
from understand call function , pointer increment make point 2nd element in array. lastly deference pointer , assign new value integer pointed to.
i find c++ pointers , references can confusing maybe can explain me behavior.
edit: question not duplicate of increment, preincrement , postincrement
because not pre- vs. post-increment rather increment on pointers return of function.
edit2:
tweaking function
int ** setvalue(int k) { int* x = &vals[k]; return &x; }
you can use
*(++(*setvalue(1))) = 42;
you can't call unary operator (++
) on not variable. setvalue(0)
treated value.
so,
*(setvalue(0)++) = 42;
should be
*(setvalue(0) + 1) = 42;
Comments
Post a Comment