Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too many elements in an array!

Sorry if this is a noob question :( .

Piece of C code.

int array[5];
int cnt;

for(cnt = 0; cnt <= 10; cnt+=1)
{
      array[cnt] = cnt;
}

Should give an error, right? No! Works fine! But why is that? It seems that -in the first line- an array of more than the double size (11) is defined. You can even access array[5 to 10] later on. And that is confusing me. It stops working when you define array[4 or less] ...

Thanks in advance.

like image 239
spiderman Avatar asked Apr 27 '09 20:04

spiderman


2 Answers

It may happen to work with your particular compiler and computer, but you shouldn't count on it.

The behaviour of your code according to the C language specification is undefined. This means that it might do what you hope, or it might cause your computer to crash, or it might cause demons to fly out your nose.

Unlike higher-level languages such as Java and C#, C trusts you and does not perform explicit checks on the bounds of arrays. You are supposed to be responsible and not tread outside the boundaries of the array.

like image 73
Simon Nickerson Avatar answered Sep 22 '22 02:09

Simon Nickerson


This only "works" if your definition of "works" is synonymous with "hasn't crashed yet".

like image 29
Don Neufeld Avatar answered Sep 23 '22 02:09

Don Neufeld