建立一个Student的对象数组包含学号,姓名,年龄,用三种指针形式输出(做个纪念)~
建立一个Student的对象数组包含学号,姓名,年龄,用三种指针形式输出计科的某个同学对这个作业进行求助,然后我就顺便弄了一段,哇,话说不知道那个同学的老师看见这段代码有何感想,不管了,自己弄了很长时间,其实关键是看看怎么整合代码,代码比较短的时候或者看不出什么,但代码多的时候却可以明显提高代码重用率以及方便分块维护,就当是个纪念吧~
程序代码:
/*建立一个Student的对象数组包含学号,姓名,年龄,用三种指针形式输出*/ #include<stdio.h> #include<stdlib.h> #include<string.h> #include<assert.h> #define ID id #define NAME name #define AGE age #define FREE(p) \ do \ { \ free(p); \ p=NULL; \ }while (0) #define CLEAN while (getchar()!='\n') #define GET_ARRAY_SIZE( arr ) \ sizeof (arr)/sizeof (*arr) #define _SCANF( id,name,age ) \ \ do \ { \ printf("请输入ID:"); \ scanf("%u",(id)); \ CLEAN; \ \ printf("请输入姓名:"); \ myScanf((name),sizeof (name)); \ \ printf("请输入年龄:"); \ scanf("%u",(age)); \ CLEAN; \ puts(""); \ }while (0) #define SCANF_STUDENT( INDEX,STU ) \ { \ printf("现在输入第%u个学生的信息:\n",( unsigned )(INDEX)+1); \ _SCANF(&STU#ID,STU#NAME,&STU#AGE); \ } #define _PRINT( id,name,age ) \ printf("ID:%u\n姓名:%s\n年龄:%u\n\n",(id),(name),(age)) #define PRINT_STUDENT( stu ) \ \ do \ { \ _PRINT \ ( \ stu#ID,stu#NAME,stu#AGE \ ); \ }while (0) #define FOR_EACH( i,num,size ) \ for ((i)=(num);(i)!=(size);++(i)) #define STUDENT Student typedef struct STUDENT { unsigned ID; char NAME[10]; unsigned AGE; }STUDENT; void nodeMal( void**,size_t ); char* myScanf( char*,size_t ); void input1( STUDENT*,size_t ); void input2( STUDENT*,size_t ); void input3( STUDENT*,size_t ); void print( STUDENT*,size_t ); int main ( void ) { const size_t size=2; STUDENT* stu=NULL; void (*p_input[])( STUDENT*,size_t )= \ { input1,input2,input3 }; const size_t p_size=GET_ARRAY_SIZE(p_input); size_t i; nodeMal(( void** )&stu,size); FOR_EACH(i,0,p_size) { printf("现在用第%u种方法输入%u个学生的数据数据:\n",( unsigned )i+1,( unsigned )size); (*p_input[i])(stu,size); print(stu,size); } FREE(stu); return 0; } void nodeMal(void** p,size_t size) { *p=malloc(size); assert(*p); memset(*p,0,size); } char* myScanf(char* s,size_t size) { char* p=NULL; fgets(s,size,stdin); if ((p=strchr(s,'\n'))!=NULL) *p='\0'; else scanf("%*[^\n]%*c"); return s; } void input1( STUDENT* stu,size_t size ) { size_t i; FOR_EACH(i,0,size) SCANF_STUDENT(i,stu[i].); } void input2( STUDENT* stu,size_t size ) { size_t i; FOR_EACH(i,0,size) SCANF_STUDENT(i,(*(stu+i)).); } void input3( STUDENT* stu,size_t size ) { STUDENT* p; FOR_EACH(p,stu,stu+size) SCANF_STUDENT(p-stu,p->); } void print( STUDENT* stu,size_t size ) { size_t i; puts("学生信息输出如下:\n"); FOR_EACH(i,0,size) PRINT_STUDENT(stu[i].); }
[此贴子已经被作者于2018-3-29 15:42编辑过]