C: 运算符 -> 和 *

标签 c pointers struct postfix-operator

<分区>

在下面的例子中:

typedef struct {
    const char *description;
    float value;
} swag;

typedef struct {
    swag *swag;
    const char *sequence;
} combination;

typedef struct {
    combination numbers;
    const char *make;
} safe;

int main()
{
    swag gold = {"GOLD!", 1000000.0};
    combination numbers = {&gold, "6502"};
    safe s = {numbers, "RAMACON250"};

    //Correct handling
    printf("Result: %s \n", s.numbers.swag->description);

    //Faulty handling
    // printf("Result: %s \n", s.numbers.(*swag).description);

    return 0;
}

为了接收“GOLD!”,以下行是正确的

printf("Result: %s \n", s.numbers.swag->description);

但为什么以下内容不正确,因为 (*x).yx->y

相同
printf("Result: %s \n", s.numbers.(*swag).description);

我在编译过程中收到以下错误:

C:\main.c|26|error: expected identifier before '(' token|)

最佳答案

就用

printf("Result: %s \n", ( *s.numbers.swag).description);

根据 C 语法,后缀表达式 . 定义如下

postfix-expression . identifier

所以你可以这样写

( identifier1 ).identifier2

但你可能不会写

identifier1.( identifier2 )

回到您的程序,您甚至可以编写

printf("Result: %s \n", ( *( ( ( s ).numbers ).swag ) ).description);

关于C: 运算符 -> 和 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48149827/

相关文章:

c - gdb:在特定库中设置断点

c - (另一个)关于 C 循环和数据结构的问题

c++ - c++传递包含指针的const结构-如何在值之间移动?

c - 用C编写和读取结构?

C - 给定地址而不是指针时的内存分配操作

c# - 从 C# 访问 C DLL 结构中的数组

c - inet_ntop : No space left on device

c - 将指针分配给空指针时出现段错误

c++ - 如何在指针数组中查找指针数

c - 自由 char*,当在 C 中作为 void 传递时