[英]Conflicting return types
我正在执行一个递归程序,但遇到有关冲突类型的错误:
void* buddyMalloc(int req_size)
{
// Do something here
return buddy_findout(original_index,req_size); // This is the recursive call
}
void *buddy_findout(int current_index,int req_size)
{
char *selected = NULL;
if(front!=NULL)
{
if(current_index==original_index)
{
// Do something here
return selected;
}
else
{
// Do Something here
return buddy_findout(current_index+1,req_size);
}
}
else
{
return buddy_findout(current_index-1,req_size);
}
}
错误:
buddy.c: At top level: buddy.c:76: error: conflicting types for ‘buddy_findout’ buddy.c:72: note: previous implicit declaration of ‘buddy_findout’ was here
请注意,我在其中定义的buddy.c文件不包含main文件,并且与其他几个.c文件链接。
如果没有原型,就不能在正确定义函数之前使用它。 buddy_malloc()
在原型或定义之前使用buddy_findout()
,编译器会将其视为定义。
原型buddy_findout()
定义之前buddy_Malloc()
或定义buddy_findout()
定义之前buddy_Malloc()
我建议原型,即:
void *buddy_Malloc(int);
void *buddy_findout(int, int);
...就在您最后的#include
这样可以避免在定义事物的顺序上造成任何混淆。 另外,在指定大小时,请考虑使用size_t
(体系结构上可用的最大无符号int类型),而不要使用带符号整数。
这是同时使用这两种方法的代码(已更正)。 方法1-使用原型:
void *buddy_Malloc(int);
void *buddy_findout(int, int);
void* buddyMalloc(int req_size)
{
//Do something here//
return buddy_findout(original_index,req_size); //This is the recursive fn I call//
}
void *buddy_findout(int current_index,int req_size)
{
char *selected = NULL;
if(front!=NULL)
{
if(current_index==original_index)
{
//Do something here//
return selected ; //
}
else
{
//Do Something here//
return buddy_findout(current_index+1,req_size);
}
}
else
{
return buddy_findout(current_index-1,req_size);
}
}
和方法2,只需重新排序:
void *buddy_findout(int current_index,int req_size)
{
char *selected = NULL;
if(front!=NULL)
{
if(current_index==original_index)
{
//Do something here//
return selected ; //
}
else
{
//Do Something here//
return buddy_findout(current_index+1,req_size);
}
}
else
{
return buddy_findout(current_index-1,req_size);
}
}
void* buddyMalloc(int req_size)
{
//Do something here//
return buddy_findout(original_index,req_size); //This is the recursive fn I call//
}
在某些圈子中,不需要静态函数原型的人被认为是一门艺术 ,它表明了在编写代码之前,该程序已被计划在某个人的脑海中。 关于这两种方法,我没有太多要说的,除了向仍在学习C语言基本知识的人推荐原型(甚至是静态函数)之外。
如果buddy_*
将公开供其他模块使用,则您确实需要原型。 很难说出您是否打算将它们设为静态。
编辑:
如果要将原型放在外部头文件中,则需要使用include防护以确保每个模块仅包含一次(并且不要将它们重新定义为完全相同的东西)。
这是一个示例buddy.h
:
#ifndef BUDDY_H
#define BUDDY_H
void *buddy_Malloc(int);
void *buddy_findout(int, int);
#endif /* BUDDY_H */
然后,预处理器将阻止您的模块抛出该错误。
我想这一定是缺少原型。
添加功能原型
void *buddy_findout(int current_index,int req_size);
在函数buddyMalloc
之前
buddy_findout
被声明为返回指向void的指针,但是在一个地方,您尝试返回selected
,这是指向char的指针。 正如其他人已经指出的那样,您还需要buddy_findout
的原型:
void *buddy_findout(int, int);
void *buddy_malloc(int req_size) {
return buddy_findout(original_index,req_size);
}
void *buddy_findout(int current_index, int req_size) {
// ...
if (current_index == original_index)
return (void *)selected;
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.