Reputation: 3529
char arr1 [0];
arr1[50] = 'A';
char arr2 [0] = {1, 1, 1, 1, 1}; //gives compiler warning
Why do the above compile normally?
And how come only the second gives me a warning?
Upvotes: 1
Views: 107
Reputation: 78903
Both declarations should give you a compile time error since declaring an array of length 0
is a "constraint violation" a type of error that any compiler must capture if it is conforming to the C standard.
char arr2 [0] = {1, 1, 1, 1, 1};
Has an additional constraint violation, namely that there are more initializers than elements in the array. Your compiler only seems to capture that one.
In contrast to that
arr1[50] = 'A';
is just run time behavior that is undefined by the standard and the compiler can do anything that pleases with it. A good compiler could also easily detect that one.
In summary, you should perhaps look into getting yourself a better, more recent compiler.
Upvotes: 1
Reputation: 64404
The first one compiles normally because the compiler will typically not realize that a[50] = 0
is attempting to assign a value outside the array allocated memory. The behavior at runtime is undefined: it may crash, terminate the program, format your harddrive, or not do anything at all.
The second one gives a warning because the array initializer on the right does not match the array declaration on the left. It would be like writing int x = "a string"
.
Upvotes: 1
Reputation: 4666
"char arr2 [0] = {1, 1, 1, 1, 1};" would give you an error since you are declaring arr2 as an array of zero element and initializing it with 5 elements. Most likely the compiler would complain/warn you of having excess elements in the array initializer. You can either do "char arr2[] = {1, 1, 1, 1, 1};" and C would implicitly figure out the storage OR you can explicitly specify the number of elements: "char arr2[5] = {1, 1, 1, 1, 1};"
Also, "arr1[50] = 'A';" is a bad idea when you are delcaring arr1 as an array of size zero: "char arr1 [0];". Just declare it so that it can have enough elements to include the value that you are adding at index 50.
Upvotes: 0