c - 如何定义具有指针类型项的结构?
问题描述
我有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 结构的值
推荐阅读
- python - 找到最小的 n 使得第 n 个 Bernstein 近似是好的,误差最多为 10^(-8)
- php - 在 PHP 中放入函数时创建对象实例失败?
- amazon-web-services - 使用 REST API 检索 Amazon CloudWatch 警报
- c# - C#:如何将参数化值传递给 System.Data.Entity.SqlSquery
- authentication - 在 Devexpress xaf asp 上注册新用户
- apache-spark - 使用结构化流对 Stream-Static Inner Joins 的输出进行聚合
- android - 未解决的参考:Facade Flutter 插件
- c - 文本文件 fscanf 问题
- laravel - 404 找不到 laravel 路由
- django - 如何过滤外键项?