結構體指標變數與結構體成員指標變數
阿新 • • 發佈:2019-02-09
C程式碼
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct student{
- char *name;
- int score;
- struct student* next;
- }stu,*stu1;
- int main(){
- stu.name = (char*)malloc(sizeof(char)); /*1.結構體成員指標需要初始化*/
- strcpy(stu.name,"Jimy");
- stu.score = 99;
- stu1 = (
- stu1->name = (char*)malloc(sizeof(char));/*3.結構體指標的成員指標同樣需要初始化*/
- stu.next = stu1;
- strcpy(stu1->name,"Lucy");
- stu1->score = 98;
- stu1->next = NULL;
- printf("name %s, score %d /n ",stu.name, stu.score);
- printf(
- free(stu1);
- return 0;
- }
寫測試程式碼的過程中我明白了,同事所說的二叉樹遍歷演算法中所用的左子樹和右子樹指標不需要初始化,其實是這樣的,左子樹和右子樹指向的必須是二叉樹節點型別的結構體指標(你填一個長度相同的指標也可以),而該結構體指標是需要初始化的(見註釋2),也就是並沒有通過malloc來分配記憶體,而是將另一個指標的值賦給它
頓時覺得挺無語的,確實,看了很多大學裡的教材,對於二叉樹的遍歷等演算法定義的結構體無非是以下形式
- struct node{
- int data;
- struct node* lchild, rchild;
- };
使用時都直接的
- struct node* root;
- root = (struct node*)malloc(sizeof(struct node));
- root->data = 3;
- struct node* nlchild;
- nlchild = (struct node*)malloc(sizeof(struct node));
- root->lchild = nlchild;
- nlchild->data = 2;
- struct node* nrchild;
- nlrchild = (struct node*)malloc(sizeof(struct node));
- root->rchild = nrchild;
- nrchild->data = 4;
這樣子給人造成一種錯覺好像結構體成員指標是不用初始化的。
可是,只要是指標,要使用它前就必須保證指標變數的值是一個有效的值;否則,它指向的記憶體一定是垃圾資料!
C語言的記憶體管理很重要,集魄力和麻煩於一身,看你自己的心態如何了。如果你積極的面對,你正在控制一切;如果你覺得煩躁,你正不得不控制一切。C仍舊是博大精深的語言,信C哥!
/*附加:仍舊是指標*/
- stu1 = (struct student*)malloc(sizeof(struct student));/*2.結構體指標需要初始化*/
這一句可能會有人把sizeof裡邊也填成struct student*
可以理解這樣的行為,因為stu本來就是struct student*,可是這樣子你就沒有為結構體分配足夠的記憶體,使用中會因為記憶體錯誤同樣報錯的。
當然,僅僅為結構體指標分配記憶體還不夠,結構體成員指標仍然需要分配記憶體,如下
- stu1->name = (char*)malloc(sizeof(char));