我有一个 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/