所以我正在尝试在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;
}
老实说,我无法弄清楚我做错了什么......我的逻辑是,因为我是将我的结构作为指针键入,所以在我在内存中创建结构后,我将能够轻松单步执行随后的列表。我逻辑中的缺陷在哪里?
编辑初始问题已修复(我忘记了struct 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
出于某种原因,似乎我的程序在第一次迭代后没有将我的更改存储在内存中。关于我做错了什么想法?
再次,任何帮助将不胜感激,谢谢。
答案 0 :(得分:4)
在您的结构定义中,您有struct node
没有下划线。
你最好有一个前瞻声明
typedef struct node node;
然后声明你的结构
struct node {
...
node *next;
};
无需使用此下划线内容并将*
隐藏在typedef
中。这只会让你容易混淆。
答案 1 :(得分:1)
字符串文字"like this"
的类型为const char*
,而不是char*
,因为它们是不可变的。
修正您的声明以使const char*
并且警告将消失。
答案 2 :(得分:1)
我认为struct member'next'必须声明为(node_ *)类型。正如所写的那样(node_ **)