c - 如何定义一个指针类型的结构体?

标签 c pointers struct typedef void-pointers

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

最佳答案

我不会用 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 结构的值

关于c - 如何定义一个指针类型的结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58037953/

相关文章:

c - 在 C 中调用 strtok 之前从字符串中删除子字符串

c++ - QT ntp 并消除差异

c - 使用指针指向2D数组的乘法

file - go - 使用 struct 读取二进制文件

c - 连接 int 和字符串时 sprintf 无法正常工作

c - C中的双指针

C - 没有函数指针的动态函数调用

c - 错误 :free(): invalid next size (fast)

swift - 搜索struct创建的对象

c - Turbo C 在我的笔记本电脑上无法工作