结构体做函数参数(三)

拥有回忆 提交于 2019-12-03 07:50:34

结构体中含有二级指针的内存分配和释放

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct Teacher
{
    char name[64];
    char *alisname;
    char **stuname;
    int age;
    int id;
}Teacher;

void printTeacher(Teacher *array,int num)
{
    int i = 0;
    for (; i < num; i++)
    {
        printf("age : %d\n",array[i].age);
    }
}

void sortTeacher(Teacher *array,int num)
{
    int i,j;
    Teacher tmp;
    
    for (i = 0; i < num; i++)
    {
        for (j = i+1; j < num; j++)
        {
            if (array[i].age > array[j].age)
            {
                tmp = array[j];
                array[j] = array[i];
                array[i] = tmp;
            }
        }
    }
}

int createTeacher( Teacher **pT, int num)
{
    int i = 0, j = 0;
    Teacher *tmp = NULL;
    tmp = (Teacher *)malloc(num * sizeof(Teacher));
    if (NULL == tmp)
    {
        return -1;
    }

    memset(tmp,0,sizeof(Teacher)*num);

    for (i = 0; i < num; i++)
    {
        char **p = NULL;
        tmp[i].alisname = (char *)malloc(60);

        p = (char **)malloc(3 * sizeof(char *));
        for (j = 0;  j < 3; j++)
        {
            p[j] = (char *)malloc(120);
        }
        tmp[i].stuname = p;
    }

    *pT = tmp;
    return 0;
}

void FreeTeacher(Teacher *p, int num)
{
    int i = 0, j = 0;
    if (p == NULL)
    {
        return ;
    }

    for (i = 0; i < num; i++)
    {
        if (p[i].alisname != NULL)
        {
            free(p[i].alisname);
        }

        if (p[i].stuname != NULL)
        {
            char **myp = p[i].stuname;
            for (j = 0; j < 3; j++)
            {
                if (myp[j] != NULL)
                {
                    free(myp[j]);
                }
            }
            free(myp);
            p[i].stuname = NULL;
        }
    }
    free(p);
}

int main()
{
    int ret = 0;
    int i = 0, j = 0;
    int num = 3;
    Teacher *pArray = NULL;
    ret = createTeacher(&pArray,num);
    if (ret != 0)
    {
        printf("func createTeacher() err : %d\n",ret);
        return ret;
    }

    for(i = 0; i < num; i++)
    {
        printf("\nplease enter age:");
        scanf("%d",&(pArray[i].age));

        printf("\nplease enter alias:");
        scanf("%s",(pArray[i].alisname));

        for (j = 0; j < 3; j++)
        {
            printf("please enter student name:");
            scanf("%s",pArray[i].stuname[j]);
        }
    }

    printTeacher(pArray,num);

    sortTeacher(pArray,num);

    printf("after sort\n");
    printTeacher(pArray,num);

    FreeTeacher(pArray,num);
    return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!