The increment pointer is returned by the function

Hey I experimented a little with C / C ++ and pointers while reading here

I made myself a function to return a pointer to an int somewhere in the 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 manage the array

but this:

*(++setValue(0)) = 42;

      

does not work. Note however *setValue(0) = 42;

works

From what I understand, I call a function and I get some pointer, I increment it so that it points to the second element in my array. Finally, I cheer up the pointer and assign a new value to the integer it pointed to.

I find that C ++ pointers and references can be somewhat confusing, but maybe someone can explain this behavior to me.

EDIT: This question is NOT a duplicate of Increment, preincrement and postincrement

because it's not about pre-vs. post-increment, but rather about incrementing pointers that are the return of a function.

EDIT2:

Function setting

int **  setValue(int k) {
    int* x = &vals[k];
    return &x;
}

      

you can use

*(++(*setValue(1))) = 42;

      

+3


source to share


1 answer


You cannot call the unary operator ( ++

) on something that is not a variable. setValue(0)

considered as meaning.

So,

*(setValue(0)++) = 42;

      



it should be

*(setValue(0) + 1) = 42;

      

+5


source







All Articles