首页 > 解决方案 > 附加到链表时进行了不必要的更改

问题描述

AI 已经设法让链表发挥作用,因为它可以在其中创建一个列表存储变量,但现在我遇到了另一个我从未找到解决方案的问题。每当我通过我想要存储的变量列表运行它时,它将通过列表运行并创建正确数量的节点,但字符串变量在每次追加后都会不断变化。
例如,如果我运行:

"Dog" "cat" "house"

而不是所需的输出:

Dog
cat
house

它产生

house
house
house

我不确定它为什么一直这样做,而且我似乎无法确定头节点字符串正在被更改的位置,除非第一个实例列表为空,因此需要分配一个新的头。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>


#define EMPTY NULL;

typedef struct listnode{
  struct listnode* next;
  char* fileName;
} listnode;

struct listnode* head;

//This section of code will be dedicated to the creation and management
//of the listnode functions

listnode* createNode(char* str, listnode* next){
  listnode* tempo;
  tempo = (listnode*)malloc(sizeof(struct listnode));

  if(tempo == NULL){
    printf("Error creating space for new node.\n");
    exit(0);
  }

  tempo->fileName = str;
  tempo->next = next;

  return tempo;
}

listnode* append(listnode* head, char* str){
  listnode* temp;
  listnode* curr;

  temp = createNode(str, NULL);

  if(head == NULL){
    head = temp;
    return head;
  }
  else{
    curr = head;
    while(curr->next != NULL){
      curr = curr->next;
    }
    curr->next = temp;
    return head;
  }
}

void printNames(listnode* head){
  listnode* curr= head;

  while(curr !=NULL){
    printf("%s \n", curr->fileName);
    curr = curr->next;
  }
}

void list_free(listnode* head){
  listnode* current;
  listnode* temp;

  if(head != NULL){
    current = head->next;

    if(head !=NULL){
      current = head -> next;
      head ->next = NULL;
      while(current != NULL){
    temp = current -> next;
    free(current);
    current = temp;
      }
    }
  }
  free(head);
}


int main(int argc, char **argv){
  char *current_dir = NULL;
  DIR *direct_ptr = NULL;
  struct dirent *dir_ptr = NULL;
  unsigned int fileNum = 0;
  int c;
  listnode* head = NULL;

  current_dir = getenv("PWD");
  if(NULL == current_dir){
    printf("\n Error: Couldn't grab current directory.\n");
    return -1;
  }

  direct_ptr = opendir((const char*)current_dir);
  if(NULL == direct_ptr){
    printf("\n Error: couldn't open current directory\n");
    return -1;
  }


  for(fileNum=0; NULL != (dir_ptr = readdir(direct_ptr)); fileNum++){
    if(dir_ptr->d_name[0] != '.'){
      head = append(head, dir_ptr->d_name);
    }
  }
  printNames(head);
}

标签: clinked-list

解决方案


在 C 中,数组(如字符串)不是按值传递的。相反,它们是通过指针传递的。当您将一个 char 数组指定为函数参数时,该数组衰减为一个指针

因此,您必须要么

  1. 确保 listnode 结构成员filename指向的字符串保持有效且未被覆盖,或者
  2. 将字符串的副本存储在 listnode 结构中。

为了复制字符串,您可以使用函数strcpy. 但是,您必须在 listnode 结构中为 char 数组分配足够的空间,或者必须使用动态内存分配(例如malloc)并存储指向动态分配内存的指针。


推荐阅读