繁体   English   中英

结构字符未正确分配

[英]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) ,暗示\\0被“打印” )。 我认为这是关于我不熟悉的结构的一些挑剔的观点,但我不能为我的生活弄清楚它是什么。 随意抓取/编译/测试代码。

此外,我知道存在内存泄漏...这是一个来自更大代码的修改片段,因此许多功能不是学术上的完美。 我只是想证明我的行为。

谢谢大家!

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

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); 第一个字节将存储您的字符,第二个字节将存储字符串终结符'\\0' ,之后您可以将其打印为字符串。 您忘记使用以前的字段了:

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

您从新分配的节点打印字符串,它不会在您打印它时及时初始化。 移动你的线current = current->next; 以上printf语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM