繁体   English   中英

如何将流中的char添加到节点中?

[英]How to add char from a stream into a node?

这是我的代码。 我被困在添加流文件串到我的链表。 例如,这里有一个名为foo的文件。 在foo中,它的格式如下

12345678 12345678

1233 1389732

等等。 这意味着我得到文件的每一行,只读取第一个字符串并将其添加到列表中。 我检查了在第95行添加“a / b / c / d”。它有效。 所以插入功能正常。 问题发生在101行。我不知道为什么第二行的值覆盖了第一行的值。

这意味着,当我逐步打印列表时,它会打印出来

A / B / C / d / 12345678 /

A / B / C / d /1233分之1233/

我坚持为什么它为二线打印a / b / c / d / 12345678/1233?

对此有何建议?

#include <stdio.h>
#include <string.h> 
#include <stdlib.h>


typedef struct n{
  char *value;
  struct n *next;
} Node;


void printList(Node *head){
  Node *cur = head;
  while(cur!=NULL){
    printf("%s/", cur->value);
    cur = cur->next;
  }
  printf("\n");
}

void insertIntoList(Node **head, char *data){
  Node *newNode = malloc(sizeof(Node));
  if (newNode == NULL){
    perror("Failed to allocate a new node for the linked list");
    exit(1);
  }
  newNode->value = data;
  newNode->next = NULL;

  Node *currentList = *head;
  if(*head == NULL){    //if the linked list head is null, then add the target into linked list
    *head = newNode;
  }
  else{
    while(currentList->next!=NULL){
      currentList = currentList->next;
    }
    currentList->next = newNode;
  }
}


int main(int argc, char**argv){
  FILE *fileStream;


  size_t len = 0;
  char *line = NULL;
  Node *head = NULL;


  int j;
  for(j=1; j<argc-2;j++){
    fileStream = fopen(argv[j], "r");
    if(fileStream == NULL){
      fprintf(stderr, "could not open");
      continue;
    }
    insertIntoList(&head,"a"); /////////////Line 95
    insertIntoList(&head,"b");
    insertIntoList(&head,"c"); 
    insertIntoList(&head,"d");
    printf("here is a try\n");
    printList(head);
    while(getline(&line, &len, fileStream)!=EOF){ /////////////Line 101
          char *targetNum = strtok(line, " ");
          if(strcmp(targetNum, "\n")!=0&&strcmp(targetNum,"\t")!=0&&strcmp(targetNum," ")!=0){
            printf("*****%s\n", targetNum);
            insertIntoList(&head, targetNum);
            printf("######print head here is##########\n");
          printList(head);
          printf("######print head here is##########->\n");
          }
      }
      //printList(head);
  }
  return 0;
}

原因是,您只将指针存储在列表中,而不是实际数据中。

前4个项目都有不同的内存位置,因此它们保持不同。

但接下来的两个具有相同的内存位置,因此两者的数据相同,这是放置在该位置的最新数据。

暂无
暂无

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

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