gpt4 book ai didi

c - C 中的嵌套结构访问

转载 作者:太空宇宙 更新时间:2023-11-04 08:51:15 25 4
gpt4 key购买 nike

下面是一段示例代码:

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 它运行良好。但在这种情况下,编译器会抛出以下内容

错误:'(' 标记之前的预期标识符

在 LINE 2 中我做了类似的事情。两者有什么区别?

最佳答案

你在第 1 行错写了左括号 => (t2->tests+2)->a=1;

澄清一下:当您实际编写 t2->tests 时。这意味着您正在访问 t2 中的测试地址。您无法访问 (tests + 2),因为它会导致 t2 中出现“未知变量”。

关于c - C 中的嵌套结构访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com