所以我試圖在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_未來;.
現在我有一個問題:當我嘗試在底部通過列表步驟我的代碼打印出包含在列表中的話,我基本上不能夠逐步通過列表我保持輸出:
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
出於某種原因,似乎我的程序是不是我的存儲在第一次迭代之後,我在內存中的列表發生了變化。關於我在做什麼錯誤的任何想法?
再次,任何幫助將不勝感激,謝謝。
請不要typedef指針看起來像非指針。殺死可讀性。 – Kos
這實際上是一個很好的提示,它真的沒有發生在我身上。 你的意思是喜歡而不是typedef結構node_ *節點,我應該做一些像typedef結構node_ nodeptr? – gfppaste
@gfppaste:參見Jens的答案。 –