结构体成员和结构体指针初始化

来源:互联网 发布:苏州聚合数据 编辑:程序博客网 时间:2024/06/09 16:21
  1. #include    
  2. #include    
  3. #include    
  4.   
  5. struct student{   
  6.   char *name;   
  7.   int score;   
  8.   struct student* next;   
  9. }stu,*stu1;    
  10.   
  11. int main(){    
  12.   stu.name = (char*)malloc(sizeof(char)); /*1.结构体成员指针需要初始化*/  
  13.   strcpy(stu.name,"Jimy");   
  14.   stu.score = 99;   
  15.   
  16.   stu1 = (struct student*)malloc(sizeof(struct student));/*2.结构体指针需要初始化*/  
  17.   stu1->name = (char*)malloc(sizeof(char));/*3.结构体指针的成员指针同样需要初始化*/  
  18.   stu.next  = stu1;   
  19.   strcpy(stu1->name,"Lucy");   
  20.   stu1->score = 98;   
  21.   stu1->next = NULL;   
  22.   printf("name %s, score %d \n ",stu.name, stu.score);   
  23.   printf("name %s, score %d \n ",stu1->name, stu1->score);   
  24.   free(stu1);   
  25.   return 0;   
  26. }
0 0
原创粉丝点击