【问题标题】:How to define a structure with a pointer-type item?如何定义具有指针类型项的结构?
【发布时间】:2020-01-22 01:52:48
【问题描述】:

我有一个typedef struct,但指针类型命名为*Ptype,如下所示 -

typedef struct
{
    int InputIntArg1;
    int InputIntArg2;
    char InputCharArg1;
} *Ptype;

我想定义一个项目 (Item1) 并为其成员分配编号 (InputIntArg1 & InputIntArg2)。但是,Item1 是一个指针。是否可以不更改 typedef 命名(*Ptype)并进行正确的声明?

int main(void)
{
    Ptype Item1; // <---------- How to modify this line?
    Ptype Item2;

    Item1.InputIntArg1 = 1;
    Item1.InputIntArg2 = 7;
    Item2 = &Item1;
    printf("Num1 = %d \n", Item2->InputIntArg1);
}

【问题讨论】:

    标签: c pointers struct typedef void-pointers


    【解决方案1】:

    我不会隐藏指向带有 typedef 的结构的指针。

    也许使用:

    typedef struct
    {
        int InputIntArg1;
        int InputIntArg2;
        char InputCharArg1;
    } Type;
    

    然后你可以写:

    int main(void)
    {
        Type Item1;
        Type *Item2;
    
        Item1.InputIntArg1 = 1;
        Item1.InputIntArg2 = 7;
        Item2 = &Item1;
        printf("Num1 = %d \n", Item2->InputIntArg1);
    }
    

    那么接下来会发生什么:

    • Item1 是一个 Ptype 结构
    • Item2 是指向 Ptype 结构的指针
    • 分配Item2 = &amp;Item1; Item2 现在指向 Item1 结构
    • 现在使用 Item2 指针访问 Item1 结构的值

    【讨论】:

    • 我基本同意;尽管只要指针类型显然是带有ptr 或其他一些明显的前/后缀的指针类型,它就“没问题”。至少我已经处理了很多这样做的代码库:)
    • 我同意,有一个很大的代码库可以做到这一点。恕我直言,使用显式指针更具可读性。当然,这也取决于团队内部商定的代码风格。一个人当然应该坚持这一点。但我个人的偏好绝对是明确使用指针:)
    【解决方案2】:

    不,没有办法仅从Ptype 引用匿名结构类型本身。你能做的最好的就是在同一个类型定义中添加基类型和指针类型:

    typedef struct
    {
        int InputIntArg1;
        int InputIntArg2;
        char InputCharArg1;
    } type, *Ptype;
    

    然后只需使用type 作为实际结构,使用Ptype 作为指向它的指针。

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2019-05-04
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多