繁体   English   中英

将指针解引用为空指针?

[英]Dereferencing a pointer to a null pointer?

我正在尝试在c中构建健壮的LinkedList,而我要处理的问题之一是初始化。

struct node* list = malloc(sizeof(node))

这是初始化LList的一种明显方法,但是它将head元素的value初始化为0,这并不是我想要的。 新初始化的LList不应包含任何节点。 相反,我想做这样的事情:

struct node* list = NULL;

创建一个LList,然后添加具有以下内容的元素:

add(&list, 1);
add(&list, 2);

那基本上将取消引用&list ,测试以查看它是否为NULL ,如果是,则X否则为Y。但是,显然我是段错误的,并且想知道是否是因为我正在将指针指向空指针?

加()

  8 void add(struct node** headRef, int value) {
  9   struct node* node = *headRef;
 10   struct node* new_node = malloc(sizeof(*new_node));
 11 
 12   new_node->value = value;
 13   new_node->next = NULL;
 14 
 15   if (node == NULL) {
 16     node = malloc(sizeof(node));
 17     node = new_node;
 18   } else {
 19 
 20     while (node->next != NULL) {
 21       node = node->next;
 22     }
 23 
 24     node->next = new_node;
 25   }
 26 }

谢谢

这段代码有3个问题:

node = malloc(sizeof(node));
node = new_node;

首先,您分配了错误的字节数。 使用模式node = malloc(sizeof *node);

其次,这会泄漏内存:您将node指向刚分配的内存块。 然后,将node指向new_node所指向的对象。 这不会留下任何指向已分配块的指针。

第三, node是函数的局部变量,因此函数外部的代码看不到此更改。

我认为您的意思是整个功能应该是这样的:

void add(struct node** headRef, int value)
{
// Make the new node
    struct node* new_node = malloc(sizeof *new_node);
    new_node->value = value;
    new_node->next = NULL;

// If the list is empty then make the new node be the first node
    if ( *headRef == NULL ) 
        *headRef = new_node;

// Otherwise put this node on the end of the list
    else for ( struct node *ptr = *headRef; ; ptr = ptr->next )
    {
         if ( ptr->next == NULL )
         {
              ptr->next = new_node;
              break;
         }
    }
}

指针只是一种访问内存的机制。 不同类型的指针具有不同的访问机制。 整数指针读取4个字节,而字符指针则在引用时仅读取1个字节。

为了存储东西,您需要分配内存。 分配内存后,您可以使用不同的指针访问它。 当你写:

  new_node=(struct node*)malloc(sizeof(struct node))

这意味着您正在分配一些内存,并使用new_node指针对其进行访问。

当你写:

   node=new_node

这意味着节点将指向new_node当前引用的相同内存。您不需要为节点分配内存,因为您只是使用它访问已分配的内存。

void add(struct node** headRef, int value) {
    struct node* node = *headRef;
    struct node* new_node = malloc(sizeof(struct node));//Always mention datatype rather than mentioning a particular value;

    new_node->value = value;
    new_node->next = NULL;

    if (node == NULL) {
      //node = malloc(sizeof(node)); //Not required as you are just accessing the pre-allocated memory;

      *headRef = new_node; //Change the actual pointer rather than the local one;
    } else {

      while (node->next != NULL) {
        node = node->next;
      }

      node->next = new_node;
    }
 }

暂无
暂无

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

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