根据我目前的理解,这与正确分配内存有关。
我不明白为什么打印item->键而不调用比较功能?结构项*项已经在内存中我想?
有什么建议吗?被困了很长时间
struct item
{
char* key;
struct item *left;
struct item *right;
};
int compare(char* A, char* B){
return strcmp(A, B);
}
struct item* insert(struct item* item, char* key)
{
printf ("(%s):",key);
printf ("(%s)\n",item->key); // I can do Node->Key here
compare(item->key, key); // I cant do node->key here // Segmentation Error
}
潜在的修复?我尝试分配一个内存并将项目加载到其中。结果也一样。试试我能找到的任何东西:(
struct item* item = (struct item*) malloc(sizeof(struct item));
答案 0 :(得分:1)
您确实初始化了item
,但您没有正确分配item->key
。 item->key
仍然指向未经初始化的地方。
答案 1 :(得分:1)
在您对正在打印的内容进行澄清后,我唯一可以猜到的是您的编译器在拖拽您,并且在您compare(item->key, key);
的调用中strcmp()
内并未真正发生段错误。
printf()
检查空参数,因此如果item->key
为空,则printf()
将打印“null
”。另一方面,strcmp()
不检查null
,如果您将null
传递给它,它将会崩溃。 compare()
上的崩溃根本没有任何意义。
当然应该注意的是编辑器并不为人们所知。必须有更好的解释。