'Can someone explain why the output is like this? [duplicate]

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.



Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andreas Wenzel