簡體   English   中英

指針類型不兼容錯誤C

[英]incompatible pointer type error C

因此,我嘗試在C中實現緩存。我提供了非常精簡的代碼版本。

我不斷收到此錯誤:

prog.c: In function ‘addtolist’:
prog.c:29: warning: assignment from incompatible pointer type
prog.c:40: warning: assignment from incompatible pointer type
prog.c: In function ‘main’:
prog.c:72: warning: assignment from incompatible pointer type

從此代碼:

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

struct node_
{
    char * word;
    int filenumber;
    struct node * next;
};
typedef struct node_ * node;

node createnode()
{
    node head;
    head = malloc(sizeof(struct node_));
    head->word = NULL;
    head->next = NULL;
    return head;
}

unsigned int addtolist(node head, char * word, unsigned int limit, int fileno)
{
    unsigned int templimit = limit;
    node temp;
    node temphead = head;
    while(temphead->next != NULL)
    {
            temphead = temphead->next;
    }
    temp = malloc(sizeof(struct node_));
    temp->word =(char*) malloc(strlen(word)+ 1);
    strcpy(temp->word, word);
    temp->next = NULL;
    temp->filenumber = fileno;
    templimit = templimit - (strlen(word) + 1) - sizeof(struct node_)- sizeof(int);
    printf("templimit is size %u\n", templimit);
    if (templimit < limit && templimit > 0)
    {
            temphead->next = temp;
            limit = limit - strlen(word) - 1 - sizeof(struct node_)- sizeof(int);
            return limit;
    }
    else
    {
            free(temp->word);
            free(temp);
            return 0;
    }
}


int main()
{
    node newlist = createnode();
    int i = 0;

    unsigned int limit = 65;
    unsigned int temp = limit;

    while(temp > 0 && temp <= limit)
    {
        temp = addtolist(newlist, "Hello", temp, i);
        i++;
        printf("new limit is - \t%u\nfilenumber is - \t%d\n", temp,i);

    }
    node ptr = newlist;
    while(ptr->next != NULL)
    {
            printf("node %d contains the word %s\n", ptr->filenumber, ptr->word);
            ptr = ptr->next;
    }
    return 1;
}

老實說,我無法弄清楚我在做什么錯……我的邏輯是,由於我將結構體類型化為指針,因此在內存中創建結構體后,我將能夠輕松地完成操作。隨后的清單。 我的邏輯缺陷在哪里?

編輯最初的問題已得到解決(我在結構體node_ next;的類型聲明中忘記了下划線;

現在,我遇到另一個問題:當我嘗試單步執行代碼底部的列表以打印出列表中包含的單詞時,我基本上無法單步瀏覽列表。 我繼續輸出:

templimit is size 43
new limit is -  43
filenumber is -     1
templimit is size 21
new limit is -  21
filenumber is -     2
templimit is size 4294967295
new limit is -  0
filenumber is -     3
node 0 contains the word (null)
node 0 contains the word Hello

由於某種原因,第一次迭代后,我的程序似乎沒有將對列表的更改存儲在內存中。 關於我在做什么錯的任何想法嗎?

再次感謝您的幫助。

在結構定義中,您具有不帶下划線的struct node

你最好有一個前瞻性聲明

typedef struct node node;

然后聲明你的結構

struct node {
 ...
 node *next;
};

無需使用這些下划線內容並將*隱藏在typedef 那只會使您容易地混淆。

"like this"字符串文字具有const char*類型,而不是char* ,因為它們是不可變的。

修正聲明中的const char* ,警告將消失。

我認為結構成員'next'必須聲明為(node_ *)類型。 按照書面說明,當前為(node_ **)

暫無
暫無

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

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