【发布时间】:2016-10-18 21:39:19
【问题描述】:
此示例编译时没有警告/错误(gcc 4.8.2 -Wall):
#include <stdio.h>
int main()
{
char c;
int i;
printf("%p %02x\n",&i,c[&i]);
printf("%p %02x\n",&c,c[&c]);
// important to note that this line DOESN'T compile:
//printf("%p %02x\n",&i,c[i]);
// which makes sense as c is NOT an array, it is a char.
return 1;
}
为什么语法 c[&i] 可以编译?是故意的还是意外的? 语法 c[&i] 在语义上是否有效? (有什么有用的意思吗?)
我的输出示例:(指针每次都会改变)
0xbfb2577c b7718cea
0xbfb2577b 08
这个问题源于这里有问题的一段奇怪的代码“ch2[&i]”: C duplicate character,character by character
NOTE#0(经过反思更新)关于重复/类似问题: 这个问题不是 c 数组引用上的链接问题的重复。它是相关的,因此参考它们很有用。相关问题讨论了有效的 a[b] 和 b[a] 情况,其中 a 或 b 之一是指针,另一个是 int。这个问题处理更奇怪的情况,也许应该是无效的情况,其中 a 或 b 之一是字符。 对于C数组,为什么a[5] == 5[a]? 14 个答案 With arrays, why is it the case that a[5] == 5[a]? 字符串作为数组索引 3 个答案 String as an array index
注意 #1:编译器会发生这种情况,因为变量 c 的类型是 char,当与指针结合使用时,它可以用作数组的索引。
注意 #2:由于某种原因,c[<ptr>] 的类型计算为 <ptr> 的类型。
例如:c[&pi] 和 c[&pc] 的结果类型导致以下代码中的警告:
int *pi; char *pc; pi=&i; pc=&c;
printf("%p %02x\n",&pi,c[&pi]);
printf("%p %02x\n",&pc,c[&pc]);
关于类型“int *”或“char *”而不是“unsigned int”的警告:
c/so_cweirdchar2.c: In function ‘main’:
c/so_cweirdchar2.c:13:5: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘int *’ [-Wformat=]
printf("pi %p %02x\n",&pi,c[&pi]);
^
c/so_cweirdchar2.c:14:5: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘char *’ [-Wformat=]
printf("pc %p %02x\n",&pc,c[&pc]);
^
【问题讨论】:
-
注意
&i是一个指针。