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# - 获取指向自身内部结构的指针(不安全上下文)

go - 在结构中使用 map 的更好方法? Go编程语言练习1.4

android - 在 Android Studio 中使用预构建的共享库

C:有符号整数标记值?

c++ - 返回指向动态数组中最年轻学生的指针

c++ - 这个指针转换我做错了什么?

c - 错误: assignment to expression with array type while using selection-sort

cudaMemcpy 没有将主机矩阵复制到设备(给出段错误)

c - 这是一个使用堆栈检查 C 中括号平衡的程序,但它没有按预期工作

c - 在函数之间传递指向结构数组的指针