在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/C/ C的指針問題

C的指針問題

#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *next;
};

int main()
{
    struct Node* head;
    head->data = 1;
    head->next = NULL;
    printf("%d", head->data);
    return 0;
}

為什么這一段代碼不能運行?
另外還有 warning:'head' is uninitialized in this function ?
調試運行到 head 就崩了。。。

回答
編輯回答
喜歡你

struct Node* head; 僅僅定義了一個指針,并沒有聲明定義一個struct Node結構。

2018年1月3日 22:06
編輯回答
安于心

編譯器已經給你提示了,指針沒有初始化呀~~~

要么改成這樣:

int main()
{
    struct Node head;
    head.data = 1;
    head.next = NULL;
    printf("%d", head.data);
    
    return 0;
}

要么改成:

int main()
{
    struct Node* head;
    
    head = (struct Node*)malloc(sizeof(struct Node));
    if(head)
    {
        head->data = 1;
        head->next = NULL;
        
        printf("%d", head->data);
    }
    else
    {
        // 內存錯誤
    }
    
    return 0;
}
2017年7月28日 10:51