Reputation: 15
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?
Upvotes: 1
Views: 7695
Reputation: 310940
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 );
Upvotes: 1