-1
int one_d[] = {1,2,3};
int main()
{
    int *ptr;
    ptr = one_d;
    ptr += 3;
    printf("%d",*ptr);
    
    return 0;
}

The output is 2. But why? I expect that ptr has pointed the one_d[3] since the last assignment ptr += 3. But one_d has 3 elements. Can someone explain it to me pls? Thank you so much.

doguu
  • 1
  • 1
  • 4
    Your understanding of `*ptr` being equivalent to `one_d[3]` is correct, but `one_d[3]` is accessing the array out of bounds; valid indices are `0`, `1`, and `2`. This is [undefined behaviour](https://en.cppreference.com/w/c/language/behavior). – Oka May 01 '22 at 20:21

1 Answers1

1

Initially, ptr is pointing at one_d[0] (same as one_d), then when you add 3 to ptr, you are pointing at one_d[3].

Notice that one_d has length 3, so the last element is at index 2 not 3. This means one_d[3] is out of bounds and can be anything. The fact that it is outputting 2 is random, since it is outputting whatever is 4 bytes behind one_d[2]. The fact that you got 2 is just a coincidence.

If you change one_d to one_d[] = {1,2,3,4};, then your program will output 4.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
bhud23
  • 9
  • 2
  • Thx mate for your helping me. If it points an index that is out of bound, so we should expect just a random value right? – doguu May 01 '22 at 20:30
  • 1
    @doguu: You should not "expect" anything when invoking [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior) by accessing an array out of bounds. Anything may happen in that case, including your program crashing. That is the nature of undefined behavior. – Andreas Wenzel May 01 '22 at 20:33