-2

when I did something like this:

int arr[]={11, 12, 13, 14, 15};
int *p=arr;
*(p++) += 100;

The result of arr[1] was still 12,why?

Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23
  • 5
    Because it is a *post*-increment. Check the value of `arr[0]`. – Eugene Sh. Feb 23 '22 at 16:00
  • Because you only changed the first element. – Weather Vane Feb 23 '22 at 16:00
  • 3
    If you printed out the entire `arr` array, you would see that the first item was changed, thus would indicate to you what is happening. FYI -- It's simple things like this (printing out values) that aren't being done which leads to questions being downvoted (lack of research). – PaulMcKenzie Feb 23 '22 at 16:01

2 Answers2

1

You are adding 100 to the first element of the array arr[0] and then moving p to the next element arr[1]. This expression:

*(p++) += 100;

Is actually translated into this:

*p += 100;
++p;
Pax
  • 134
  • 5
  • so the parentheses don't work here? – HedoesnotDICE Feb 24 '22 at 04:42
  • @HedoesnotDICE The parenthesis work, but they do not do what you are thinking: they isolate `p++` from `*` operator. In turn, `(*p)++` will indeed increase the first element. – Pax Feb 25 '22 at 08:05
0

You are post-incrementing p which does not change p[1]. To change p[1] you need to pre-increment p. And then decrement p to obtain p[1].

Example: TRY IT ONLINE

#include <stdio.h>

int main(void){
    int arr[]={11, 12, 13, 14, 15};
    int *p = arr;
    *(++p) += 100;
    p--;
    printf("%d\n", p[1]);
    return 0;
}
Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23