Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring an array with 0 number of elements can still store values

I get that using negative indexes is just pure luck. But out of curiousity I tried this. I know you can declare array[0]; just like malloc(0); is legal. But how come I can store a value in array[0]?

#include <stdio.h>
#include <conio.h>
int main(void)
{
    int i;
    int array[0];
    array[0] = 5;
        printf("%d\n",array[0]);
    getch();
}
like image 926
Programmerboi Avatar asked Oct 07 '22 12:10

Programmerboi


1 Answers

Such a 0 sized array is a constraint violation in standard C, you compiler should not let you get away with this without giving you a diagnostic. If it doesn't tell you something then, that must be an extension that your compiler vendor has added to its C dialect.

Don't rely on such extensions.

Regardless whether or not you'd declare the array with size 0, C has no imposed bound checking of array or pointer access. A good modern compiler should still give you a warning, though, if the excess of the bounds is known at compile time.

like image 145
Jens Gustedt Avatar answered Oct 11 '22 01:10

Jens Gustedt