堆内存澄清

时间:2014-04-15 02:39:15

标签: c typedef heap-memory

我遇到了我提供的代码问题。 我不确定我的代码有什么问题。如果您能清楚指出我的代码有什么问题,我将不胜感激。基本上,我正在尝试为人的身高和体重分配记忆并计算BMI。

编辑:当我运行此代码时,我希望它要求用户名,获取用户名。询问用户体重和身高,然后计算打印结果,但是当我执行此代码时。我得到的只是

H的BMI为= inf

谢谢,

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

typedef struct {

    float heightInMeters;
    int weightInMeters;
}Person;
float bodyMassIndex (Person*p)
{
    return (*p).weightInKilos / ((*p).heightInMeters*(*p).heightInMeters);
}

int main()
{
    Person *x = (Person *)malloc(sizeof(Person));
    Person weightInKilos;
    Person heightInMeters;
    char name;

    printf("What is your name?\n");
    scanf("%s", &name);
    sleep(1);

    printf("Please enter your weight in Kilos\n");
    scanf("%d", &weightInKilos);
    sleep(1);

    printf("Please enter your height in Meters\n");
    scanf("%f", &heightInMeters);

    float xBMI = bodyMassIndex(x);
    printf("%s has a BMI of = %.2f\n", &name, xBMI);

    free(x);

    x = NULL;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

在结构定义中,int weightInMeters;应为int weightInKilos;

这一行没有做任何事情:

(*x).weightInKilos;

就像写作:1 + 1;。你的意图是什么? (从技术上讲,这一行会导致未定义的行为,以评估未初始化的变量)。

char name;
scanf("%s", &name);

声明char name;表示name是单个字符。但是scanf("%s"试图读取几个字符。这将导致缓冲区溢出,带来不可预测的后果。用以下内容替换:

char name[100];
scanf("%100s", name);

这一行:

scanf("%d", &weightInKilos);

我认为你的意思是

scanf("%d", &x->weightInKilos);

最后,在这一行:

printf("%s has a BMI of = %.2f\n", &name, xBMI);

&name应为name

相关问题