简体   繁体   English

gcc编译器中的C变量声明-编译时错误

[英]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: 具有以下表达式:

  1. A[2]
  2. A[2][3]
  3. B[1]
  4. 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? 有人可以解释原因吗?

  1. You can assign 0 to A[2] , because A is an array of pointers, and you can assign 0 to a pointer (it's a NULL pointer). 您可以将0分配给A[2] ,因为A是一个指针数组,并且可以将0分配给一个指针(它是NULL指针)。
  2. You can assign 0 to A[2][3] , because at this level you're working with the int . 您可以将0分配给A[2][3] ,因为在此级别上您正在使用int
  3. You cannot assign 0 to B[1] , because B is an array of arrays, and 0 is a scalar. 您不能将0分配给B[1] ,因为B是一个数组数组,而0是一个标量。
  4. See 2. 见2。

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

  1. A[2] = 0 is correct, because A[2] = NULL is obviously correct and NULL is defined as 0. However if you try some value other than 0, you should encounter some type transition error. A [2] = 0是正确的,因为A [2] = NULL显然是正确的,并且NULL定义为0。但是,如果尝试使用非0的值,则应该遇到类型转换错误。
  2. A[2][3] = 0 is correct, in terms of syntax, as this statement is understood by the compiler as * (* (A + 2) + 3) = 0; 就语法而言,A [2] [3] = 0是正确的,因为编译器将该语句理解为*(*(A + 2)+ 3)= 0; Or more clearly, consider it as "int* p = A[2]; *(p + 3) = 0"; 更明确地说,将其视为“ int * p = A [2]; *(p + 3)= 0”;
  3. B[1] is incorrect; B [1]不正确; the superficial reason is B[1] points to an array and you cannot assign an array; 肤浅的原因是B [1]指向数组,您不能分配数组; the essential reason is that B[1] is translated into some address value by the compiler, so it cannot work as a left value. 根本原因是编译器将B [1]转换为某个地址值,因此它不能用作左值。 Or one can consider it this way: There is no corresponding memory cell for B[1]. 或者可以这样考虑:B [1]没有相应的存储单元。
  4. B[2][3] = 0 because this is how it works :) B [2] [3] = 0,因为这是这样的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM