简体   繁体   中英

how to change value of a member of a struct using a pointer

I cannot solve the following issue:

I have a struct like:

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;

When i try to access the member type (which is an enum), i can't change its value. It compiles, but when i run it i get a 'Segmentation Fault'. In my main method i have sth like this:

node_p *node1 = NULL;
node1->node_type = FRUIT;
node1->data.question = "Apple";

Does anyone know what the problem seems to be?

You have to allocate memory for the node. For example

node_p *node1 = malloc( sizeof( node_p ) );
if ( node1 != NULL )
{
    node1->node_type = FRUIT;
    node1->data.question = "Apple";
}

And do not forget to free the allocated mempry then the node will not be needed any more using function free:

free( node1 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM