C第12章-----堆

#include <stdio.h>

#include <stdlib.h>

 

//声明Person结构

//struct Person{

//    float heightInMeters;

//    int weightInKilos;

//};

 

//声明Person类型

typedef struct{

    float heightInMeters;

    int weightInKilos;

}Person;

 

//float bodyMassIndex(Person p){

//    return p.weightInKilos / (p.heightInMeters * p.heightInMeters);

//}

 

float bodyMassIndex(Person *p){

    return p->weightInKilos / (p->heightInMeters * p->heightInMeters);

}

 

int main(int argc, const char * argv[]) {

    

    //使用malloc()函数可以得到一块内存缓冲区,当程序不在使用这块缓冲区时,可以调用free()函数,释放相应的内存,将其返回给堆。

    //使用sizeof()来获得缓冲区的准确大小。

    //为一个Person结构分配内存

    Person *mikey = (Person *)malloc(sizeof(Person));

    

    //为一个Person结构分配内存

    mikey->weightInKilos = 96;

    mikey->heightInMeters = 1.7;

    

    //计算并输出BMI

    float mikeyBMI = bodyMassIndex(mikey);

    printf("mikey has a BMI of %f ", mikeyBMI);

    

    //释放占用的内存,使之能够被重用

    free(mikey);

    

    //将指针变量赋为空

    mikey = NULL;

    

    return 0;

    

//    //struct Person mikey;

//    //Person mikey;

//    mikey.heightInMeters = 1.7;

//    mikey.weightInKilos = 96;

//

//    //struct Person aaron;

//    //Person aaron;

//    aaron.heightInMeters = 1.97;

//    aaron.weightInKilos = 84;

//

//    printf("mikey is %.2f meters tall. ", mikey.heightInMeters);

//    printf("mikey weights %d kilograms. ", mikey.weightInKilos);

//    printf("aaron is %.2f meters tall. ", aaron.heightInMeters);

//    printf("aaron weights %d kilograms. ", aaron.weightInKilos);

//

//    float bmi;

//    bmi = bodyMassIndex(mikey);

//    printf("mikey has a BMI of %.2f ", bmi);

//

//    bmi = bodyMassIndex(aaron);

//    printf("aaron has a BMI of %.2f ", bmi);

//

//    return 0;

}

原文地址:https://www.cnblogs.com/turningli/p/10695781.html