簡體   English   中英

Typedef結構無法轉換為指針

[英]Typedef struct cannot be cast to pointer

我已經在多個帖子中看到了這個問題,但是我還沒有找到一個對我有很好解釋的問題。 我試圖創建一個鏈表,但是在沒有得到錯誤的情況下不能調用結構或函數,不能將其轉換為指針。 它真的困擾我。 任何幫助將不勝感激如何使其正常工作。 這是多數民眾贊成在下面的一些代碼。

typedef struct node
{
    void *data;
    struct node *next;
} node;

node *head = NULL;

node* create(void *data, node *next)
{
    node *new_node = (node*)malloc(sizeof(node));
    if(new_node == NULL)
    {
        exit(0);
    }else{

        new_node->data = data;
        new_node->next = next;
        return new_node;
    }

}

node* prepend(node *head, void *data)
{
    node *new_node = create(data,head);
    head = new_node;
    return head;
}


void preload_adz(int adz_fd)
{
    struct adz adz_info;
    char adz_data[40];
    char adz_text[38];
    int adz_delay;
    char adz_delayS[2];

    read(adz_fd,adz_data,40);
    strncpy(adz_text,adz_data + 2,40-2);
    sprintf(adz_delayS, "%c%c",adz_data[0],adz_data[1]);
    adz_delay = atoi(adz_delayS);

    adz_info.delay = adz_delay;
    strncpy(adz_info.text,adz_text,38);

    head = prepend(head, (void*)adz_info); //<---This line throws the error

    while(read(adz_fd,adz_data,40) > 0)
    {

    }
}
struct adz adz_info;

...

head = prepend(head, (void*)adz_info); //<---This line throws the error

這里的問題是adz_info不是指針,而是堆棧上的實際結構。 adz_info傳遞給函數將復制該結構。

您需要一個指向該結構的指針。 使用&獲取其地址。 一旦有了指針,就不需要將其強制轉換為void指針,該轉換是自動的。

head = prepend(head, &adz_info);

請注意,鑄造是記賬的事情。 強制轉換為void *不會將結構轉換為指針,它表示“編譯器,忽略此變量的聲明類型,只相信我這是一個void指針”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM