gpt4 book ai didi

初学者的 cstring 麻烦

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:49 29 4
gpt4 key购买 nike

我正在尝试制作一个逐行读取文件然后将读取的行放入链表的程序,我的问题是将字符串添加到列表中。看代码,在else测试中你可以看到我的问题。

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

struct list_el {
char *ord;
struct list_el * next;
};

typedef struct list_el item;

int main(int argc, char *argv[]) {
int c;
item *curr, *head;
head = NULL;
FILE *fileHandle = fopen("tresmaa.txt", "r");

while((c = fgetc(fileHandle)) != '\n' || c != EOF)
if(c == EOF) {
printf("\n");
break;
} else {
curr = (item*)malloc(sizeof(item));
curr->ord = "I cant point curr -< ord = c, how can i point the readed sentences to the value Ord?";
curr->next = head;
head = curr;
putchar(c);
}
curr = head;

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

最佳答案

curr->ord = "some string" is wrong

相反,您需要分配一个缓冲区并将字符串放入其中

例如

curr->ord = malloc( strlen(yourstring) + 1 );
strcpy(curr->ord, yourstring);

因为

curr = (item*)malloc(sizeof(item));

仅分配包含“ord”指针的结构,但不分配它指向的内容

另一件看起来有点可疑的事情是

        curr->next = head;
head = curr;

看起来更像是名称应该是“prev”而不是“next”(后进先出)

否则,如果你想要一个“普通”的 FIFO 链表只有一个头指针和一个尾指针,那么使用尾指针追加元素,同时保持头指向第一个列表元素。

关于初学者的 cstring 麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3735025/

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