c - C 中的嵌套结构访问

标签 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);
    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/

相关文章:

c# - 如何从 C# 系统托盘应用程序将 C 程序作为线程运行?

c++ - 尝试在 NetBeans 6.9.1 中包含 .h 库

c - 为什么C中局部变量的默认值是相同的?

cs50 Pset2 :Crack - help me understand something with '=='

c++ - 当从函数调用传递值时,std::tie 失败并返回 "cannot bind non-const lvalue reference"

c++ - Dev C++中的编译错误错误

Java,如何使用 computeIfAbsent computeIfPresent 来实现这个目的?

c - 成员之间不会有填充是否安全?

ios - 错误: bad receiver type 'CGSize' (aka 'struct CGSize' ) | Xcode 6.4 | iOS 8.4

arrays - 在 Dymola 中编译大型数组