简体   繁体   English

如何使用指针更改结构成员的值

[英]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函数来使用该节点:

free( node1 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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