易百教程

结构体动态内存分配

要了解结构动态内存分配,请阅读以下示例代码:

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>                    // For malloc()

typedef struct Dog Dog;            // 定义结构体的名称为:Dog

struct Dog                           // 结构体类型定义
{
    int age;
    int height;
    char name[20];
    char father[20];
    char mother[20];
};

int main(void)
{

    Dog *pdogs[50];                  // Array of pointers to structure
    int hcount = 0;                      // Count of the number of dogs
    char test = '\0';                    // Test value for ending input

    for (hcount = 0; hcount < sizeof(pdogs) / sizeof(Dog*); ++hcount)
    {
        printf_s("Do you want to enter details of a%s dog (Y or N)? ",hcount ? "nother" : "");
        scanf_s(" %c", &test, sizeof(test));
        if (tolower(test) == 'n')
            break;

        // 分配内存来保存Dog结构体
        pdogs[hcount] = (Dog*)malloc(sizeof(Dog));

        printf_s("Enter the name of the dog: ");
        scanf_s("%s", &pdogs[hcount]->name, sizeof(pdogs[hcount]->name));

        printf_s("How old is %s? ", pdogs[hcount]->name);
        scanf_s("%d", &pdogs[hcount]->age);

        printf_s("How high is %s ( in hands )? ", pdogs[hcount]->name);
        scanf_s("%d", &pdogs[hcount]->height);

        printf_s("Who is %s's father? ", pdogs[hcount]->name);
        scanf_s("%s", &pdogs[hcount]->father, sizeof(pdogs[hcount]->father));

        printf_s("Who is %s's mother? ", pdogs[hcount]->name);
        scanf_s("%s", &pdogs[hcount]->mother, sizeof(pdogs[hcount]->mother));
    }

    // 打印数据值
    printf_s("=============================\n");
    for (int i = 0; i < hcount; ++i)
    {
        printf_s("%s is %d years old, %d hands high,",
            pdogs[i]->name, pdogs[i]->age, pdogs[i]->height);
        printf_s(" and has %s and %s as parents.\n", pdogs[i]->father,
            pdogs[i]->mother);
        free(pdogs[i]);
    }
    system("pause");
    return 0;
}

执行上面示例代码,得到以下结果:

Do you want to enter details of a dog (Y or N)? y
Enter the name of the dog: goodboy
How old is goodboy? 2
How high is goodboy ( in hands )? 2
Who is goodboy's father? FGoodboy
Who is goodboy's mother? Mgoodboy
Do you want to enter details of another dog (Y or N)? n
=============================
goodboy is 2 years old, 2 hands high, and has FGoodboy and Mgoodboy as parents.