gcc 如何处理数组 [与 C 编程相关的问题]
即使使用 -Wall 选项,这也会在 gcc 中编译,不会出现错误或警告 这意味着在运行时检查数组边界,因此编译器无法检测到错误
#include<stdio.h>
int main()
{
int a[2][3][4];
a[1][2][100] = 4 ;
return 0;
}
但是,
#include<stdio.h>
int main()
{
int a[2][3];
a[1][2][100] = 4 ;
return 0;
}
这会在编译时生成错误:
$ gcc sample.c -Wall
sample.c: In function ‘main’:
sample.c:7: error: subscripted value is neither array nor pointer
为什么会这样?在这两个代码中,a[1][2][100] 是无效的。编译器仍然如何检测这是代码2而不是代码1。
特别是当每个编译器都将所有多维数组平铺为相应的单维数组时,那么编译器如何选择性地意识到代码中的这个缺陷。
对某些有正确解释的书籍或文章的解释或提及将不胜感激:)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
区别在于类型。 C 不进行边界检查,但进行(静态)类型检查。第一个示例中 a 的类型是
int[][][]
,但第二个示例中的类型是int[][]
。您所指的“扁平化”发生在代码生成中,(至少从概念上来说)是在类型检查之后。
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 isint[][]
.The "flattening" that you refer to happens in code generation, which is (conceptually, at least) after type checking.
首先,在运行时或编译时不会检查数组边界。出去要小心。
其次,第二种情况会出现错误,因为数组维度不匹配 - 您在二维数组上使用三个下标运算符 (
[]
)。仅仅因为数组恰好作为数组的数组布置在内存中,并不意味着该变量发生任何实际类型更改。数组下标在 C 标准部分6.5.2.1 数组下标中进行了描述。
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.
鉴于
编译器将确定
a[1][2]
的类型为int
。因此,访问它的元素[100]
相当于:这会给您带来关于下标值的相同错误。
Given
the compiler will determine that
a[1][2]
is of typeint
. Therefore, accessing element[100]
of this is equivalent to:This would give you the same error about the subscripted value.