c - 如何从C中的结构中打印指针变量?
问题描述
我需要在结构中打印出一个指针变量。我假设我必须取消引用,但不确定如何在没有分段错误的情况下进行。
struct HealthProfile{ //structure with pointers to all needed variables.
char *name;
char *last;
char *gender;
struct date *dob;
float *height;
float *weight;
};
void readData(){
float height;
printf("What is your name?\n");
scanf("%s", &H.name); //scan
//H.name = name;
printf("What is your last name? \n");
scanf("%s", &H.last);
//H.last = last;
printf("What is your Height name? \n");
scanf("%f", &H.height);
printf("Height: %f\n", *(H.height));
//printf("First Name: %s\n", H->name);
//printf("Last Name: %s\n", H->last);
}
我希望它打印出扫描的高度,它是一个浮点数。
解决方案
首先float height;
,你需要声明,而不是声明struct HealthProfile H;
。更好的是,在任何地方声明struct HealthProfile profile;
并替换为.H
profile
接下来,修正你的scanf()
陈述。例如
scanf("%s", &H.name);
应该
scanf("%s", profile.name);
同样改变
scanf("%f", &H.height);
至
scanf("%f", profile.height);
现在你的语法printf()
将是正确的。
但是,您仍然会遇到问题,因为没有为您的指针分配内存。name
将and字段声明last
为指针是有意义的。但是,我认为您应该声明这些值float height;
,而float weight;
不是使用指针。如果您这样做,那么您scanf()
与运营商的原始陈述&
将是正确的。
推荐阅读
- ruby-on-rails - 使用每个 Ruby Rails 在数组上计算相同的值
- c# - 无法将侦听器注册到 System.Diagnostics.Tracing.EventSource
- javascript - 状态 ReactJS 和渲染方法
- gradle - 如何定义地图
在 build.gradle - c - 可变长度数组是否以 C 中的默认 0 值开头?
- amazon-s3 - 如何在cyberduck CLI 中启用SSE-S3 (AES-256) 加密?
- bash - 如何从输出中删除行尾
- mysql - MySQL 错误 1093 - 无法在 FROM 子句中指定要更新的目标表(两个连接)
- java - xml 尖括号改为 & lt 分号
- angular - Ionic 5 Edge 浏览器侧边菜单未显示