c-不同函数中初始化指针(malloc)时出现分段错误



我正试图通过以下操作初始化一个树:

typedef struct {
    char *value;
    struct children_list *children;
} tree;
typedef struct t_children_list {
    tree *child;
    struct t_children_list *next;
} children_list;
void initializeTree(tree *root, char *input)
{
  if((root = malloc(sizeof(tree))) == NULL) { abort(); }
  root->value = input;
}
void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = NULL;
  initializeTree(my_tree, input);
}

但我有一个分割错误。为什么会发生这种情况?我正在传递一个指向函数的指针,并在其中保留内存。这错了吗?

指针'my_tree'通过值传递(这是在C中完成的唯一方法)

因此my_tree基本上是COPIED的,"root"的赋值对"my_tree"变量没有任何影响。

你想取回一个指针,所以把一个指针传给一个指针(**),然后init*root来实际修改我的树

void initializeTree(tree **pRoot, char *input)
{
  if((*pRoot = malloc(sizeof(tree))) == NULL) { abort(); }
  *pRroot->value = input;
}
void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = NULL;
  initializeTree(&my_tree, input);
}

或者根本不通过,但返回:

tree *initializeTree(char *input)
{
  tree *root = NULL;
  if((root = malloc(sizeof(tree))) == NULL) { abort(); }
  root->value = input;
  return root;
}
void main()
{
  // Create the tree
  char *input = "aaaaaa";
  tree *my_tree = initializeTree(input);
}

最新更新