0

I was trying to use dynamic arrays in my project, but I can't understand why I can do this:

int *a;
a = new int[1];
a[100]=2;

cout << a[100] << endl;

I mean, I created the array 'a' which can store 1 element, so why am I able to use the 100th element of the array? It shouldn't exist, should it?

  • 10
    Same reason you can pick up and run away with the ball in basketball, even though "in basketball you cannot hold and run with the ball". – Kerrek SB May 30 '16 at 20:12
  • 2
    Because you are allowed to do stuff that doesn't work. You're accessing memory you don't should access - all bets are off - it might seem like it works, but it really doesn't. – jpw May 30 '16 at 20:14
  • @KerrekSB Brilliant. :-) – skypjack May 30 '16 at 20:14
  • @skypjack: Thanks, but I didn't come up with that. I got that from another comment here. But I do like the analogy. – Kerrek SB May 30 '16 at 20:16
  • Pointers are numerical representations of adresses. For instance, `*(a + 50)` is also legal and it's the same as `a[50]`. Look at offset operator on this [reference page](http://www.cplusplus.com/doc/tutorial/pointers/). – Lasoloz May 30 '16 at 20:18
  • 2
    Possible duplicate of [No out of bounds error](http://stackoverflow.com/questions/9137157/no-out-of-bounds-error) Also similar: http://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why – Fantastic Mr Fox May 30 '16 at 20:19
  • Btw, `a[100]` would be the 101st element, not the 100th. Array indices are 0 based. – Baum mit Augen May 30 '16 at 20:23
  • 3
    @KerrekSB I like this one -- "My driver's license was suspended, but why can I still go in a car and drive it?" – PaulMcKenzie May 30 '16 at 20:25

1 Answers1

1

Some basic stuff:
Your array is stored in memory, every cell has its own address. The name of your array a points to the place in memory where it starts. From there a[0], a[1] or just a[index] is the same thing as you'd type*(a+index) - it gets/sets value placed under (a+index) index in a memory.

In fact you can overwrite any of these addresses even if they aren't being used by your variables (arrays etc.). Of course you shouldnt do this, but your compilator won't be mad (you can also declare variable-length arrays, compilator might not care, but you should be aware of that).

I tried to make it as simple as possible, there is no need to elaborate, I believe.

mtszkw
  • 2,717
  • 2
  • 17
  • 31