Question

I am having issue with the code that i provided. I am not quit sure what is wrong with my code. I would greatly appreciate if you can clearing point out what is wrong with my code. basically, i am trying to allocate memory for person height and weight and calculate BMI.

edited: When i run this code, i would like it to ask for user name, get user name. ask user weight and height and calculate then print result but when i execute this code. all i am getting is

H has a BMI of = inf

Thanks,

#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;
}
Was it helpful?

Solution

In the struct definition, int weightInMeters; should be int weightInKilos;.

This line doesn't do anything:

(*x).weightInKilos;

It is like writing: 1 + 1; . What was your intention here? (Technically this line causes undefined behaviour for evaluating an uninitialized variable).

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

The declaration char name; means that name is a single character. But scanf("%s" tries to read several characters. This will cause a buffer overflow with unpredictable consequences. Replace those with:

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

This line:

scanf("%d", &weightInKilos);

I assume you meant

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

Finally, in this line:

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

&name should just be name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top