Consider the following code (it came about as a result of this discussion):
#include <stdio.h>
void foo(int (*p)[]) { // Argument has incomplete array type
printf("%d
", (*p)[1]);
printf("%d
", p[0][1]); // Line 5
}
int main(void) {
int a[] = { 5, 6, 7 };
foo(&a); // Line 10
}
GCC 4.3.4 complains with the error message:
prog.c: In function ‘foo’:
prog.c:5: error: invalid use of array with unspecified bounds
Same error message in GCC 4.1.2, and seems to be invariant of -std=c99
, -Wall
, -Wextra
.
So it's unhappy with the expression p[0]
, but it's happy with *p
, even though these should (in theory) be equivalent. If I comment out line 5, the code compiles and does what I would "expect" (displays 6
).
Presumably one of the following is true:
- My understanding of the C standard(s) is incorrect, and these expressions aren't equivalent.
- GCC has a bug.
I'd place my money on (1).
Question: Can anyone elaborate on this behaviour?
Clarification: I'm aware that this can be "solved" by specifying an array size in the function definition. That's not what I'm interested in.
For "bonus" points: Can anyone confirm that MSVC 2010 is in error when it rejects line 10 with the following message?
1><snip>prog.c(10): warning C4048: different array subscripts : 'int (*)[]' and 'int (*)[3]'
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…