使用二级指针,初始化一级指针

 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 }

猜你喜欢

转载自www.cnblogs.com/wangchaomahan/p/9954032.html