【问题标题】:adding items to Linked List and allocing space将项目添加到链接列表并分配空间
【发布时间】:2015-06-24 20:25:32
【问题描述】:

这是一个用于链表的节点。

struct DataNode
{
    char data[3];
    struct DataNode *nextData;
};

我这里有一个函数:

void addDataNode(struct DataNode **DataHead, char *data)
{
    struct DataNode *temp = (struct DataNode*)(malloc(sizeof(struct DataNode)));
    struct DataNode *current = *DataHead;
    if(current == NULL){
        current = temp;
        current->nextData = NULL;
        strcpy(current->data, data);
    }else{
        while(current->nextData != NULL){
            current = current->nextData;
        }
        current->nextData = temp;
        strcpy(current->nextData->data, data);
    }
}

在我的主要,我有

struct DataNode *DataHead = NULL;

所以我用

调用函数
char test[] = "Qu";
addDataNode(&DataHead, test);

但是,在函数之外,DataHead 保持为 NULL。这是为什么呢?

【问题讨论】:

    标签: c linked-list


    【解决方案1】:

    因为你没有在你的addDataNode 函数中修改*DataHead;您只能从中读取。您有两个选择:要么删除 current 变量并改用 *DataHead(始终),要么在返回之前调用 *DataHead = current

    另外,strcpy 是错误的。你想要strdup,否则你会进入未定义的内存。

    【讨论】:

      【解决方案2】:

      问题的原因是函数addDataNode太复杂了,很难看出它是否在所有路径中都设置了DataHead。:)

      事实上,这在函数的代码 sn-p 中被遗忘了

      if(current == NULL){
          current = temp;
          current->nextData = NULL;
          strcpy(current->data, data);
      }else{
      

      我建议按照以下方式重写函数

      void addDataNode( struct DataNode **DataHead, const char *data )
      {
          struct DataNode *temp = malloc( sizeof( struct DataNode ) );
      
          if ( temp )
          {
              const size_t n = sizeof( temp->data );
      
              temo->nextData = NULL;
              strncpy( temp->data, data, n );
              temp->data[n-1] = '\0'; 
      
              if ( *DataHead == NULL )
              { 
                  *DataHead = temp;
              }
              else
              {
                  struct DataNode *current = *DataHead;
      
                  while ( current->nextData ) current = current->nextData;
      
                  current->nextData = temp;
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        你永远不会在你的函数中对 DataHead 做任何事情,除了将其中的内容复制到 current 中,所以它指向的东西(如果它指向任何东西)可能会改变,指针DataHead 本身不会。

        【讨论】:

          猜你喜欢
          • 2021-12-23
          • 1970-01-01
          • 2019-11-29
          • 2015-04-16
          • 2015-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多