【问题标题】:Preceding the name of a typedef with *在 typedef 的名称前加上 *
【发布时间】:2020-05-25 09:05:18
【问题描述】:

我最近发现,在 C 中定义 typedef 结构时,可以在变量前面加上 *。

这是我正在谈论的一个例子(*book 就是这种情况):

typedef struct item {
    int id;
    float price;
} *book, pencil;

我真的不明白这是怎么回事。

这 3 个变量在数据类型方面是否等效?

struct item *foo;
book bar;
pencil *foobar;

【问题讨论】:

  • 第一个与第三个相同,但由于您创建了typedef,因此毫无意义。第二个与第三个相同,但将指针隐藏在typedef 后面被认为是不明智的。第三种是通常的方式。
  • 你的title应该是Preceding the name of a typedef with *,(book不是变量)。

标签: c variables struct typedef


【解决方案1】:

都具有相同的类型 = 指向 struct item 的指针。

书籍类型 IMO 很危险,因为它在 typedef 中隐藏了指针,从而降低了代码的可读性(对人类而言)并且容易出错

【讨论】:

    【解决方案2】:

    看一个例子

    #include <stdio.h>
    
    typedef char  *ptr1;   //This all are same
    typedef char * ptr2;
    typedef char*  ptr3;
    
    int main()
    {
        printf("%zu\n",sizeof(ptr1));
        printf("%zu\n",sizeof(ptr2));
        printf("%zu\n",sizeof(ptr3));
    
        return 0;
    }
    

    输出:

    8
    8
    8
    

    在 64 位机器上见 Demo

    输出为 8,因为它是 x86-x64 中指针的大小(在 32 位中为 4)

    你的情况

    #include <stdio.h>
    
    typedef struct item 
    {
        int id;
    //    float price;  // I comment this line for clarity
    }*book, pencil;
    
    int main()
    {
        printf("%zu\n",sizeof(book));
        printf("%zu\n",sizeof(pencil));
    
        return 0;
    }
    

    输出:

    8
    4
    

    Demo

    谢谢。

    【讨论】:

      猜你喜欢
      • 2013-07-17
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多