Reputation: 2024
This compiles in gcc with no errors or warnings even with -Wall option meaning that array bounds are checked at run-time and hence compiler can't detect the error
#include<stdio.h>
int main()
{
int a[2][3][4];
a[1][2][100] = 4 ;
return 0;
}
However,
#include<stdio.h>
int main()
{
int a[2][3];
a[1][2][100] = 4 ;
return 0;
}
this generates an error while compiling as :
$ gcc sample.c -Wall
sample.c: In function ‘main’:
sample.c:7: error: subscripted value is neither array nor pointer
Why is this so ? in both the two codes a[1][2][100] is invalid . Still how can the compiler detect this is code2 and not in code1.
Specially when every compiler flattens all multidimensional array into corresponding single dimension arrays, then how can the compiler be selectively aware of this flaw in the code.
Explanation or mention of some book or article where the proper explanation resides will be gratefully accepted :)
Upvotes: 2
Views: 516
Reputation: 37930
Given
int a[2][3];
the compiler will determine that a[1][2]
is of type int
. Therefore, accessing element [100]
of this is equivalent to:
int x;
x[100] = 4;
This would give you the same error about the subscripted value.
Upvotes: 2
Reputation: 143234
The difference is the types. C does no bounds checking but it does do (static) type checking. The type of a in your first example is int[][][]
but the type in the second example is int[][]
.
The "flattening" that you refer to happens in code generation, which is (conceptually, at least) after type checking.
Upvotes: 5
Reputation: 224972
First, array bounds are not checked at runtime or at compile time. Be careful out there.
Second, your second case gives an error because you have a mismatch in array dimension - you're using three subscript operators ([]
) on a 2D array. Just because the array happens to be laid out in memory as an array of arrays doesn't mean there is any actual type changing going on with the variable.
Array subscripting is described in the C standard section 6.5.2.1 Array subscripting.
Upvotes: 4