gpt4 book ai didi

c - 如何在c中存储具有相同内存位置的值?

转载 作者:行者123 更新时间:2023-11-30 16:55:19 25 4
gpt4 key购买 nike

如果我有一个包含内容的文件流

123 1234

1223 124235

21432 325

在我的程序中,我逐行读取文件并将每行的第一个目标存储到我的列表中。这些行具有相同的位置,当我运行程序时,它将继续指向最新的数据并将其放入列表中。这意味着如果我在 while 循环中有一个名为 printL() 的函数。它将打印

123/

1223/1223/

21432/21432/21432/

而不是

123/

123/1223/

123/1223/21432
#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, " \t\r\n");
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;
}

最佳答案

为了保留从strtok()返回的每个加载字段的内容,只需在调用insertIntoList()之前添加一个strdup() > 检查是否不是空指针后。

In your code, if you compare the value of both line and targetNum are the same. If fact, the strtok() function returns a pointer to the input string and keep the pointer for the next argument.

替换以下代码:

    char *targetNum = strtok(line, " \t\r\n");
printf("*****%s\n", targetNum);
insertIntoList(&head, targetNum);

由那个人:

    char *targetNum = strtok(line, " \t\r\n");
if (targetNum != NULL) {
printf("*****%s\n", targetNum);
insertIntoList(&head, strdup(targetNum));
}

关于c - 如何在c中存储具有相同内存位置的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com