首页 > 解决方案 > 如何从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);
}

我希望它打印出扫描的高度,它是一个浮点数。

标签: c

解决方案


首先float height;,你需要声明,而不是声明struct HealthProfile H;。更好的是,在任何地方声明struct HealthProfile profile;并替换为.Hprofile

接下来,修正你的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()与运营商的原始陈述&将是正确的。


推荐阅读