Dereferencing Person?

I tried the code in chapter 12 where it modified BMICalc, but I had to dereference mikey in the call to bodyMassIndex to get it to compile and run.

Here is my code:

#include <stdio.h>
#include <stdlib.h>     // needed for malloc and free

// Here is the declaration of the type Person
typedef struct {
    float heightInMeters;
    int weightInKilos;
} Person;

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

int main(int argc, const char * argv[]) {
    
    // Allocate memory for one Person struct
    Person *mikey = malloc(sizeof(Person));
    Person *aaron = malloc(sizeof(Person));
    
    // Fill in two members of the struct
    mikey->heightInMeters = 1.7;
    mikey->weightInKilos = 96;
    aaron->heightInMeters = 1.97;
    aaron->weightInKilos = 84;
    
    // Print out the BMI of the original Person
    float mikeyBMI = bodyMassIndex(*mikey);         // dereference by adding '*' before Person
    printf("mikey has a BMI of %.2f\n", mikeyBMI);
    float aaronBMI = bodyMassIndex(*aaron);
    printf("aaron has a BMI of %.2f\n", aaronBMI);
    
    // Let the memory be recycled
    free(mikey);
    free(aaron);
    
    // Forget where it was
    mikey = NULL;
    aaron = NULL;
    
    return 0;
}

I am a fan of Breaking Bad - I can see that you know how to cook high-grade stuff :slight_smile:

bodyMassIndex function could also be coded like this:

float bodyMassIndex (const Person * p)
{
    return p->weightInKilos / (p->heightInMeters * p->heightInMeters);
}

And then would be invoked like this:

Person * mikey = malloc (sizeof (Person));
assert (mikey);
...
float mikeyBMI = bodyMassIndex (mikey); 

Thanks ibex. I missed that in the code in the book.