【发布时间】:2020-05-14 02:40:55
【问题描述】:
我在将所有值存储到通用链接列表时遇到问题,我的链接列表完全适用于普通用户键盘输入,但是当我尝试从文件存储值(字符串)时,发生了一些奇怪的事情,它只存储文件的最后一个值。
我已经检查了我的 addToList() 函数,但它没有任何问题。
P.s 但我觉得要么我打印错误,要么我从文件读取到链接列表是错误的。
谢谢。
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include "LinkedListItems.h"
#define MAX 10000
int main()
{
printf("Testing MissileFIle.txt");
void* secondStr;
//Had to malloc the thing
secondStr = (void*)malloc(1*sizeof(char));
FILE* missileFile;
missileFile = fopen("missiles.txt", "r");
if(missileFile == NULL)
{
printf("The file is empty");
}
number_list_t* missileList = calloc(1, sizeof(number_list_t));
void* input;
//Have to allocate the input
input = malloc(1*sizeof(void*));
//this is to read the data into the second Str
while(fgets(secondStr,MAX,missileFile) != NULL)
{
//Let just print out first just to test my memory
printf("%s\n",secondStr);
//Right now its only reading one string so far which is really weird AFFFFF
addTolist(missileList,secondStr);
}
//Gotta declare another list just to print out the list
number_node_t* current = missileList->head;
while(current != NULL)
{
//There is something wrong with this line
printf("%s\n",current-> number);
current = current-> next;
}
fclose(missileFile);
}
输出: 测试 MissileFile.txt
飞溅
单身
V线
h线
单人 单身的 单身的 单身的 单身的 单人
typedef struct NumberNode
{
//It can store any data type
void* number;
struct NumberNode* next;
}number_node_t;
//List of Nodes
typedef struct NumberList
{
number_node_t* head;
int count; //This is not nesssary but it can be useful for counting how many variables
}number_list_t;
void addTolist(number_list_t* list, void* newNumber)
{
//tem[ = newNode]
number_node_t* newNode = calloc(1,sizeof(number_node_t));
newNode->number = newNumber;
newNode->next = list->head;
list->head = newNode;
}
输入数据: 单身的 溅 单身的 V线 h线 单人
【问题讨论】:
-
newNode->number = newNumber;复制的是指针,而不是字符串。 -
是的,但这对仅读取最后一个元素有什么影响
-
secondStr = (void*)malloc(1*sizeof(char));这是几个问题中的第一个。 -
如果我删除该行,它仍然显示相同的输出,并没有真正改变任何东西
-
@Obamaself 不要忽略编译器的警告,这些警告往往会在以后咬你。
标签: c linked-list