首页 > 解决方案 > 如何定义具有指针类型项的结构?

问题描述

我有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);
}

标签: cpointersstructtypedefvoid-pointers

解决方案


我不会隐藏指向带有 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 = &Item1;Item2 现在指向 Item1 结构
  • 使用 Item2 指针,您现在正在访问 Item1 结构的值

推荐阅读