1. 程式人生 > >結構體指標變數與結構體成員指標變數

結構體指標變數與結構體成員指標變數

C程式碼 複製程式碼
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. struct student{   
  5. char *name;   
  6. int score;   
  7. struct student* next;   
  8. }stu,*stu1;    
  9. int main(){    
  10.   stu.name = (char*)malloc(sizeof(char)); /*1.結構體成員指標需要初始化*/
  11.   strcpy(stu.name,"Jimy");   
  12.   stu.score = 99;   
  13.   stu1 = (
    struct student*)malloc(sizeof(struct student));/*2.結構體指標需要初始化*/
  14.   stu1->name = (char*)malloc(sizeof(char));/*3.結構體指標的成員指標同樣需要初始化*/
  15.   stu.next  = stu1;   
  16.   strcpy(stu1->name,"Lucy");   
  17.   stu1->score = 98;   
  18.   stu1->next = NULL;   
  19.   printf("name %s, score %d /n ",stu.name, stu.score);   
  20.   printf(
    "name %s, score %d /n ",stu1->name, stu1->score);   
  21.   free(stu1);   
  22. return 0;   
  23. }  



寫測試程式碼的過程中我明白了,同事所說的二叉樹遍歷演算法中所用的左子樹和右子樹指標不需要初始化,其實是這樣的,左子樹和右子樹指向的必須是二叉樹節點型別的結構體指標(你填一個長度相同的指標也可以),而該結構體指標是需要初始化的(見註釋2),也就是並沒有通過malloc來分配記憶體,而是將另一個指標的值賦給它

頓時覺得挺無語的,確實,看了很多大學裡的教材,對於二叉樹的遍歷等演算法定義的結構體無非是以下形式

C程式碼 複製程式碼
  1. struct node{   
  2. int data;   
  3. struct node* lchild, rchild;   
  4. };  


使用時都直接的

C程式碼 複製程式碼
  1. struct node* root;   
  2.  root = (struct node*)malloc(sizeof(struct node));   
  3.  root->data = 3;   
  4. struct node* nlchild;   
  5.  nlchild = (struct node*)malloc(sizeof(struct node));   
  6.  root->lchild = nlchild;   
  7.  nlchild->data = 2;    
  8. struct node* nrchild;   
  9.  nlrchild = (struct node*)malloc(sizeof(struct node));   
  10.  root->rchild = nrchild;   
  11.  nrchild->data = 4;   


這樣子給人造成一種錯覺好像結構體成員指標是不用初始化的。

可是,只要是指標,要使用它前就必須保證指標變數的值是一個有效的值;否則,它指向的記憶體一定是垃圾資料!
C語言的記憶體管理很重要,集魄力和麻煩於一身,看你自己的心態如何了。如果你積極的面對,你正在控制一切;如果你覺得煩躁,你正不得不控制一切。C仍舊是博大精深的語言,信C哥!

/*附加:仍舊是指標*/

C程式碼 複製程式碼
  1. stu1 = (struct student*)malloc(sizeof(struct student));/*2.結構體指標需要初始化*/


這一句可能會有人把sizeof裡邊也填成struct student*
可以理解這樣的行為,因為stu本來就是struct student*,可是這樣子你就沒有為結構體分配足夠的記憶體,使用中會因為記憶體錯誤同樣報錯的。
當然,僅僅為結構體指標分配記憶體還不夠,結構體成員指標仍然需要分配記憶體,如下

C程式碼 複製程式碼
  1. stu1->name = (char*)malloc(sizeof(char));