[英]How to print pointer variable from a structure in C?
I need to print out a pointer variable within a structure.我需要在结构中打印出一个指针变量。 I assume i must de-reference but am not sure how without getting a segmentation fault.
我假设我必须取消引用,但我不确定如何不出现分段错误。
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);
}
I want it to print out the scanned in height which is a float.我希望它打印出扫描的高度,这是一个浮点数。
First of all, instead of declaring float height;
首先,不是声明
float height;
, you need to declare struct HealthProfile H;
,需要声明
struct HealthProfile H;
. . Better yet, declare
struct HealthProfile profile;
更好的是,声明
struct HealthProfile profile;
and replace H
everywhere with profile
.并用
profile
替换H
无处不在。
Next, fix your scanf()
statements.接下来,修复您的
scanf()
语句。 For example例如
scanf("%s", &H.name);
should be应该
scanf("%s", profile.name);
Similarly change同样变化
scanf("%f", &H.height);
to到
scanf("%f", profile.height);
Now your syntax for printf()
will be correct.现在您的
printf()
语法将是正确的。
However, you will still have problems because non of your pointers have been allocated memory.但是,您仍然会遇到问题,因为没有为您的指针分配内存。 Declaring the
name
and last
fields as pointers makes sense.将
name
和last
字段声明为指针是有意义的。 However, I think you should declare float height;
但是,我认为您应该声明
float height;
and float weight;
和
float weight;
instead of using pointers for these values.而不是对这些值使用指针。 If you do so, then your original
scanf()
statements with the &
operator will be correct.如果这样做,那么带有
&
运算符的原始scanf()
语句将是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.