Incrementing pointer (ptr++) and (*ptr++)

后端 未结 5 1512
被撕碎了的回忆
被撕碎了的回忆 2021-01-07 14:33

I was revisiting pointers when I had this doubt.

int *ptr;
int arr[5] = {10,20,30,40,50};
ptr = &arr[0];

Now printf(\"Value: %d\"

5条回答
  •  独厮守ぢ
    2021-01-07 14:58

    The first snippet is obvious: it prints what ptr points to, i.e. 10.

    The second one, moves the pointer forward of one element, which then points to the next element, i.e. 20.

    The third snippet is exactly the same as the previous one, because its first instruction increments the pointer and returns the unincremented value, which is dereferenced, but its result is discarded; what is dereferenced in the printf is the incremented pointer, which now points to 30.

    The last snippet is different: ++*ptr is ++(*ptr); *ptr dereferences ptr (which already points to 30), yielding 30, and ++ increments such value, which becomes 31.

提交回复
热议问题