簡體   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