结构体做函数参数
结构体值栈空间内存模型
{ 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 main() { int i = 0; Teacher Array[3]; int num = sizeof(Array)/sizeof(Array[0]); for(i = 0; i < num; i++) { printf("\nplease enter age:"); scanf("%d",&(Array[i].age)); } printTeacher(Array,num);// sortTeacher(Array,num); printf("after sort\n"); printTeacher(Array,num); return 0; }
结构体堆空间内存模型
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct Teacher { char name[64]; 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; } } } } Teacher *createTeacher(int num) { Teacher *tmp = NULL; tmp = (Teacher *)malloc(num * sizeof(Teacher)); if (NULL == tmp) { return NULL; } return tmp; } void FreeTeacher(Teacher *p) { if (p != NULL) { free(p); } } int main() { int i = 0; int num = 3; Teacher *pArray = NULL; pArray = createTeacher(num); for(i = 0; i < num; i++) { printf("\nplease enter age:"); scanf("%d",&(pArray[i].age)); } printTeacher(pArray,num); sortTeacher(pArray,num); printf("after sort\n"); printTeacher(pArray,num); FreeTeacher(pArray); return 0; }