c - 链表:读取C中的字符串

标签 c string linked-list

我需要从文件中读取字符串(逐行)并将它们存储到链接列表中。我可以从文件中读取并打印它们。但是,我有如何将它们存储到链接列表的问题。我尝试创建链接列表并保存它们,如下所示:

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


typedef struct node
{
    char data[256];
    struct node *next;

} node_t;

node_t *head = NULL;
node_t *current = NULL;

int main(int argc, char const *argv[])
{
    char temp = 'Hello';
    insertToHead(temp);
    return 0;
}

void insertToHead(char *word) 
{
    node_t *link = (node_t *) malloc(sizeof(node_t));

    link->data = strcpy(link->data , word);

    link->next = head;
    head = link;
}

最佳答案

问题很多。

我修复了这里,现在程序至少可以编译:

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


typedef struct node
{
    char data[256];
    struct node *next;

} node_t;

node_t *head = NULL;
node_t *current = NULL;

void insertToHead(char *word) 
{
    node_t *link = (node_t *) malloc(sizeof(node_t));

    strcpy(link->data , word);

    link->next = head;
    head = link;
}

int main(int argc, char const *argv[])
{
    char *temp = "Hello";
    insertToHead(temp);
    return 0;
}

您确实应该学习如何读取编译器的输出。

关于c - 链表:读取C中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39858338/

相关文章:

java - 在Java中解析字符串以提取数据

c - 从 fgets() 输入中删除尾随换行符

java - 练习单链表实现,被我的列表反转方法抛出 NullPointerException 难住了

c - 单链表C,打印

C 函数调用的自定义 X86_64 调用约定

c - Nsight Eclipse 5.5 标识符未定义

c++ - 用于 MP3、AAC、WAV 的跨平台 (C/C++) 音频库

c - 创建 Linux 模块时运行 Makefile(在 C 中)时出错

ios - 使用组合字符串从 url 快速加载图像

java - 递归地反转Java中的链表