-3
int main()
{
    int a[3]={1,2,3};

    int *b;

    b=&a[10];

    printf("%u\n",b);

    printf("%d",*b);

}

I thought that the above program would give me an error as a is a collection of only 3 data items, and b=&a[10]; by this b stored the address of the 11th data member of a. But in place of error it gives the address of 11th data member.

Size of the array is 3 and but it can store the variables beyond of its size! so how does it possible?

Sampad
  • 7
  • 1
    It's not giving you the *address of 11th data member*. It's giving you the random content of memory beyond the end of the array. – Ken White Jan 22 '17 at 05:21
  • I did not get you, Sir can you please explain it little bit? @KenWhite – Sampad Jan 22 '17 at 05:38
  • 1
    I explained it. So does the linked post. – Ken White Jan 22 '17 at 05:41
  • local arrays must have constant size at compile-time as you do with `int a[3]`. `b` is not an array but it is a pointer to an integer (element[10]) and as you can see `a[10]` is not an element of the array so you have UB. – Raindrop7 Jan 31 '17 at 12:23

1 Answers1

-7

Yes, this usually works, because C and C++ don't check these things.

BUT this may cause exception on different operating systems, and may also cause an exception on your own code sometime in the future. This is an unknown behavior stuff, and you should avoid it.

halfer
  • 19,824
  • 17
  • 99
  • 186
Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
  • 3
    "Yes, this usually works" - No, it does not! It is un**defined** behaviour. – too honest for this site Jan 22 '17 at 06:30
  • 1
    NMDV, yet aside from "this usually works" is an overstatement and "C ... don't check" which is better as "C is not specified nor required to check", the answer does not address the title question: "dimension of an array ... cannot be changed" which is certainly false with code lacking UB. – chux - Reinstate Monica Jan 22 '17 at 07:17
  • I think your edit was too much about you, and was essentially "trust me, I am right". Answers should focus on code, not the author. Hope that helps! – halfer Jan 31 '17 at 11:41