使用二級指標,初始化一級指標
阿新 • • 發佈:2018-11-13
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 enum 5 { 6 Success,NameErr,SexErr,StrNumErr,ScoreErr 7 }; 8 typedef struct stu 9 { 10 char *name; 11 char *sex; 12 char *strNum; 13 float *score; 14 }STU; 15 int init(STU ** p) 16 { 17 *p = (STU *)malloc(sizeof(STU));//*p就是ps,申請一塊空間裡面存放4個不同型別的指標,將首地址賦值給ps 18 //初始化一級指標,使這4個不同型別的指標都有所指向 19 (*p)->name = (char *)malloc(sizeof(100)); 20 if((*p)->name == NULL) 21 return NameErr; 22 (*p)->sex = (char *)malloc(sizeof(char)); 23 if((*p)->sex == NULL) 24 return SexErr;25 (*p)->strNum = (char *)malloc(sizeof(30)); 26 if((*p)->strNum == NULL) 27 return StrNumErr; 28 (*p)->score = (float *)malloc(sizeof(float)); 29 if((*p)->score == NULL) 30 return ScoreErr; 31 return Success; 32 } 33 int main(void) 34 { 35 STU * ps = NULL;36 37 int ret = init(&ps); 38 if(ret != Success) 39 return -1; 40 strcpy(ps->name,"wahaha"); 41 *(ps->sex) = 'x'; 42 strcpy(ps->strNum,"語文"); 43 *(ps->score) = 66.5; 44 45 printf("姓名:%s\n性別:%c\n科目:%s\n分數:%.2f\n",ps->name,*(ps->sex),ps->strNum,*(ps->score)); 46 return 0; 47 }