c - 如何从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 。

最佳答案

首先,您需要声明struct HealthProfile H;,而不是声明float height;。更好的是,声明 struct HealthProfile profile; 并将所有位置的 H 替换为 profile

接下来,修复您的 scanf() 语句。例如

scanf("%s", &H.name);

应该是

scanf("%s", profile.name);

同样改变

scanf("%f", &H.height);

scanf("%f", profile.height);

现在您的 printf() 语法将是正确的。

但是,您仍然会遇到问题,因为没有为您的指针分配内存。namelast 字段声明为指针会使感觉。但是,我认为您应该声明 float height;float Weight; 而不是使用这些值的指针。如果您这样做,那么带有 & 运算符的原始 scanf() 语句将是正确的。

关于c - 如何从C中的结构中打印指针变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55736187/

相关文章:

CLion 中 C 文件的自定义文件模板

c - 如何理解和完成下面提供的嵌套循环挑战

C:通过格式字符串注入(inject)读取比格式字符串更多的字节

c++ - 指向结构体指针的点运算符

c++ - 压力-ng : Writing an application program using execv to invoke stress-ng commands and return if it is success or failure

c - 在 C 中的两个服务器之间传递数据的最佳方式?

c - C中的可重入和可重入?

检查数字中的偶数或奇数 `1` 位

c - 使用 C 使用 strftime() 获取缩写时区

c - 如何在c中返回一个数组