结构字符未正确分配

Struct Char not Assigning properly

我正在尝试制作链表类型的数据结构,目前它只有一个 char 作为数据,但我无法正确分配它。当我运行以下代码时:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

FILE* outfile;
FILE* infile;

int linkedlist_size;
struct linked_list
{
    char* data;
    struct linked_list* next;
    struct linked_list* previous;
};

int main()
{
    outfile = fdopen(STDOUT_FILENO,"w");
    infile = fdopen(STDIN_FILENO,"r");

    struct linked_list line_buffer;
    struct linked_list* current = &line_buffer;
    int linkedlist_size = 0;

    int input_char;
    char input_cast;
    for (input_char = fgetc(infile); (input_char != EOF && input_char != '\n') ;input_char = fgetc(infile))
    {
        input_cast = input_char;
        current->data = malloc(sizeof(char));
        (current->data)[0] = input_cast;
        linkedlist_size++;
        current->next = malloc(sizeof(struct linked_list));
        current = current->next;
        printf("\nMy address is: %p",current);
        printf("\nMy number is: %d",input_char);
        printf("\nMy char cast is: %c",input_cast);
        printf("\nMy char is: %s",current->data);
    }

    return 0;
}

使用 gcc ll_test.c、运行 和 ./a.out 编译,并使用 something 作为键盘输入,我得到以下输出:

My address is: 0x10558a0
My number is: 115
My char cast is: s
My char is: (null)
My address is: 0x1055cf0
My number is: 111
My char cast is: o
My char is: (null)
My address is: 0x1055d30
My number is: 109
My char cast is: m
My char is: (null)
My address is: 0x1055d70
My number is: 101
My char cast is: e
My char is: (null)
My address is: 0x1055db0
My number is: 116
My char cast is: t
My char is: (null)
My address is: 0x1055df0
My number is: 104
My char cast is: h
My char is: (null)
My address is: 0x1055e30
My number is: 105
My char cast is: i
My char is: (null)
My address is: 0x1055e70
My number is: 110
My char cast is: n
My char is: (null)
My address is: 0x1055eb0
My number is: 103
My char cast is: g
My char is: (null)

这意味着字母正确进入 STDIN,被正确解释(输入 \n 后循环停止)并且转换正确,但赋值不是在职的。对于它的价值,我还尝试将 linked_list.data 设为常规 char 并直接分配(通过 current->data = input_cast)并收到类似的结果(空白输出,而不是 (null),暗示[=22=] 是 "printed")。我认为这是关于我不熟悉的结构的一些挑剔点,但我无法终生弄清楚它是什么。请随意 grab/compile/test 代码。

此外,我知道存在内存泄漏...这是从较大的代码体中修改的片段,因此许多功能都不是学术上的完美。我只是想展示我得到的行为。

谢谢大家!

编辑:如下所述,错误是我在切换到下一个空节点后试图打印当前节点的字符。我犯了愚蠢的逻辑错误。

printf("\nMy char is: %s",current->data); 

应该是

printf("\nMy char is: %c", *(current->data)); 

printf("\nMy char is: %c", current->data[0]); 

也就是说,格式说明符应该用于单个 char 而不是字符串,并且需要取消引用数据指针才能获取字符。如果仍然不清楚,C 中的字符串是 NUL 终止的 字符序列。你只有一个字符而不是字符串。

您需要分配 2 个字节,如下所示:current->data = malloc(2);第一个字节将存储您的字符,第二个字节将存储字符串终止符 '[=12=]',之后您可以将其打印为字符串。您忘记使用之前的字段,您可以:

 current->next = malloc(sizeof(struct linked_list));
 current->next->previous=current;
 current = current->next;

你从新分配的节点打印你的字符串,它没有在你打印它的时候被初始化。将行 current = current->next; 移到 printf 语句上方。