c - 堆内存澄清

标签 c typedef heap-memory

我提供的代码有问题。 我不确定我的代码有什么问题。如果您能明确指出我的代码有什么问题,我将不胜感激。基本上,我试图为人的高度和体重分配内存并计算体重指数。

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

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;
}

最佳答案

在结构体定义中,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

关于c - 堆内存澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23073746/

相关文章:

无法理解为什么一行最多可以有 MAX_LINE/2 个单词

c++ - 在类定义之前使用类成员函数指针 C++

c++ - 将 __attribute__ 与 typedef 结合使用

c - 访问冲突读取位置 0x73726573

c - 为什么 printf ("%s\n", "123456789"+ 3);//输出 : "456789"

javascript - 如何增加 EsLint 内存以避免 `JavaScript heap out of memory`?

java - 如何检测低堆情况以进行监控和警报?

java - Play Framework - 无法为对象堆预留足够的空间

c - OpenMP 嵌套循环,代码在做什么?

C++ 模板类型定义