C variable declaration in gcc compiler - compile time error
Assume the following C variable declaration:
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.
A) 1, 2 and 4 only
B) 2, 3 and 4 only
C) 2 and 4 only
D) 4 only
I have tried this on a gcc compiler. I assigned the value '0' to all the above variables. Only the third one showed an error. I can't really understand the reason. Can someone please explain the reason?
- You can assign 0 to
A[2]
, becauseA
is an array of pointers, and you can assign 0 to a pointer (it's a NULL pointer). - You can assign 0 to
A[2][3]
, because at this level you're working with theint
. - You cannot assign 0 to
B[1]
, becauseB
is an array of arrays, and 0 is a scalar. - See 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. 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.
Assigning to A[2]
works because you're just pointing that array element to some other value, in this case an int
.
- 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][3] = 0 is correct, in terms of syntax, as this statement is understood by the compiler as * (* (A + 2) + 3) = 0; Or more clearly, consider it as "int* p = A[2]; *(p + 3) = 0";
- B[1] is incorrect; the superficial reason is B[1] points to an array and you cannot assign an array; the essential reason is that B[1] is translated into some address value by the compiler, so it cannot work as a left value. Or one can consider it this way: There is no corresponding memory cell for B[1].
- B[2][3] = 0 because this is how it works :)
精彩评论