3

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;
Community
  • 1
  • 1
xuma202
  • 1,074
  • 1
  • 10
  • 22
  • 1
    This is clearly not a duplicate of the linked question. – mjs Apr 22 '15 at 16:01
  • Isn't this a duplicate? Shouldn't `j = setValue(0); j++; *j = 7;` be equivalent to `*(++setValue(0)) = 7;` and not `*(setValue(0)++) = 7;` (note the pre vs post increments). – Uyghur Lives Matter Apr 22 '15 at 17:02
  • You are right but but neither `*(++setValue(0)) = 7;` nor `*(setValue(0)++) = 7;` work as explained by @Eregrith What you mentioned was not meant to be the actual question but was a bug inside it – xuma202 Apr 22 '15 at 17:22

1 Answers1

5

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;
Eregrith
  • 4,263
  • 18
  • 39
  • Thank you. I now noticed that with tweaking the function to return an int** One can use *((*setValue(1))++) = 42; – xuma202 Apr 22 '15 at 15:47