arrayscpost-incrementpre-increment

why doesn't the result of an array member changed when have assigned it?


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?


Solution

  • 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;
    }