C语言中的嵌套结构访问
下面是一段示例代码:C语言中的嵌套结构访问,c,compiler-errors,C,Compiler Errors,下面是一段示例代码: typedef struct Test{ int a; struct Test *T; }T1; typedef struct Test_2{ T1 *tests; }T2; T2 *t2; T1 *t1; int main(){ t2=(T2*)malloc(sizeof(T2)); t1=(T1*)malloc(sizeof(T1)*4); t2->tests=(T1*)malloc(sizeof(T1)*4);
typedef struct Test{
int a;
struct Test *T;
}T1;
typedef struct Test_2{
T1 *tests;
}T2;
T2 *t2;
T1 *t1;
int main(){
t2=(T2*)malloc(sizeof(T2));
t1=(T1*)malloc(sizeof(T1)*4);
t2->tests=(T1*)malloc(sizeof(T1)*4);
t2->(tests+2)->a=1; //LINE 1
(t1+2)->a=2; //LINE 2
printf("%d\n%d",t2->tests[1].a,t1[2].a);
}
我只是运行了一些代码并制作了这个示例,因为我对输出感到困惑。
如果我使用t2->tests[2]。a=1
它运行良好。但在本例中,编译器抛出以下命令
错误:在“(”标记之前应该有标识符
在第2行中,我做了类似的事情。两者之间的区别是什么?您在第1行错误地写了左括号=>(t2->tests+2)->a=1;
澄清一下:当您实际编写t2->tests
时。这意味着您正在访问t2中的测试地址。您无法访问(tests+2)
,因为这会导致t2中出现“未知变量”。这让我想起了K&R示例“Tree
”结构..:p