[英]how to change value of a member of a struct using a pointer
我無法解決以下問題:
我有一個像這樣的結構:
enum node_type {
FRUIT,
QUESTION
};
typedef enum node_type type;
struct node {
type node_type;
union node_info {
char *fruit;
char *question;
}data;
struct node *left;
struct node *right;
};
typedef struct node node_p;
當我嘗試訪問成員類型(這是一個枚舉)時,我無法更改其值。 它可以編譯,但是當我運行它時,出現“分段錯誤”。 在我的主要方法中,我有這樣的事情:
node_p *node1 = NULL;
node1->node_type = FRUIT;
node1->data.question = "Apple";
有人知道問題出在哪里嗎?
您必須為該節點分配內存。 例如
node_p *node1 = malloc( sizeof( node_p ) );
if ( node1 != NULL )
{
node1->node_type = FRUIT;
node1->data.question = "Apple";
}
並且不要忘記釋放分配的內存,然后將不再使用free函數來使用該節點:
free( node1 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.