[英]C variable declaration in gcc compiler - compile time error
Assume the following C variable declaration: 假定以下C变量声明:
int *A[10], B[10][10];
Of the following expressions: 具有以下表达式:
A[2]
A[2][3]
B[1]
B[2][3]
Which will not give compile time errors if used as left hand sides of assignment statements in a C program. 如果用作C程序中赋值语句的左侧,则不会产生编译时错误。
A) 1, 2 and 4 only A)仅1、2和4
B) 2, 3 and 4 only B)仅2、3和4
C) 2 and 4 only C)仅2和4
D) 4 only D)仅4
I have tried this on a gcc compiler. 我已经在gcc编译器上尝试过了。 I assigned the value '0' to all the above variables.
我为上述所有变量分配了值“ 0”。 Only the third one showed an error.
只有第三个显示错误。 I can't really understand the reason.
我真的不明白原因。 Can someone please explain the reason?
有人可以解释原因吗?
A[2]
, because A
is an array of pointers, and you can assign 0 to a pointer (it's a NULL pointer). A[2]
,因为A
是一个指针数组,并且可以将0分配给一个指针(它是NULL指针)。 A[2][3]
, because at this level you're working with the int
. A[2][3]
,因为在此级别上您正在使用int
。 B[1]
, because B
is an array of arrays, and 0 is a scalar. B[1]
,因为B
是一个数组数组,而0是一个标量。 Break the declaration into: 将声明分为:
int *A[10];
int B[10][10];
You can see that A[10]
is really an array of pointers , while B[10][10]
is an array of integer arrays. 您可以看到
A[10]
实际上是一个指针数组,而B[10][10]
是一个整数数组。 The reason why you cannot assign an integer to B[1]
is because B[1]
is supposed to be of type int[]
(an array), and you can't overwrite it with an int
value. 之所以不能为
B[1]
分配整数,是因为B[1]
应该是int[]
类型(数组),并且不能用int
值覆盖它。
Assigning to A[2]
works because you're just pointing that array element to some other value, in this case an int
. 分配给
A[2]
是可行的,因为您只是将数组元素指向其他值,在本例中为int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.