結構體成員和結構體指針初始化

  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. }
發佈了33 篇原創文章 · 獲贊 10 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章