初学者的 cstring 麻烦

标签 c linked-list cstring

我正在尝试制作一个逐行读取文件然后将读取的行放入链表的程序,我的问题是将字符串添加到列表中。看代码,在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/

相关文章:

c - MSVC : Error mapping a structure to an array of offsetof

c - 为什么一元 * 运算符没有约束 "the operand shall not be a pointer to void"?

将字符转换为短字符

代码出现段错误或从未完成其运行

java - 消息队列和命令队列类似吗?

c - 如何在C中将一个 float 拆分为两个整数

c++ - 双向链表复制构造函数和程序崩溃

C:生成缓冲区

c++ - MFC 的 CString 的奇怪行为

c++ - 文件无法打开,在调试器之外运行会导致段错误 (c++)