结构体做函数参数

2018-09-13  本文已影响6人  带着白卡去旅行

结构体做函数参数
demo:输入老师年龄 并且排序【大小】
实现方案:1:数组 2:指针

注意:Teacher 数据结构 是一级指针 int 型是0级指针

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

typedef struct Teacher
{
char name[64];
int age;
int id;

}Teacher;

//结构体数组 3 输入老师的年龄,排序

void printfTeacher(Teacher*array,int num)
{

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

}

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


void main()
{
    int i = 0;
    Teacher  Array[3];
    int num = 3;
    for  (i=0;i<3;i++)
    {
        printf("\nplease input age:");
        scanf("%d",&(Array[i].age));
    }

    //打印老师年龄
    /*for ( i=0;i<3;i++)
    {
        printf("age:%d\n",Array[i].age);

    }*/
    printf("排序前:\n");
    printfTeacher(Array, num);
    
    //排序
    printf("排序后:\n");
    sortTeacher(Array, num);
    printfTeacher(Array, num);


    //printf("hello....\n");
    system("pause");
    return;

}

方案二:指针形式


Teacher* craetTeacher(int num)
{

    Teacher *tmp = NULL;
    tmp = (Teacher*)malloc(sizeof(Teacher)*num);
    if (tmp==NULL)
    {
        return NULL;
    }
}

void FreeTeacher(Teacher*p)
{
    if (p!=NULL)
    {
        free(p);
    }
}

void main()
{
    int i = 0;

    int num = 3;

    Teacher *pArray = NULL;
    pArray = craetTeacher(num);
    for  (i=0;i<3;i++)
    {
        printf("\nplease input age:");
        scanf("%d",&(pArray[i].age));
    }

    //打印老师年龄
    
    printf("排序前:\n");
    printfTeacher(pArray, num);
    
    //排序
    printf("排序后:\n");
    sortTeacher(pArray, num);
    printfTeacher(pArray, num);

    FreeTeacher(pArray);

    //printf("hello....\n");
    system("pause");
    return;

}
上一篇 下一篇

猜你喜欢

热点阅读