2013-10-05 54 views
0

我在C中有一个函数,它正在崩溃我的代码,我很难弄清楚发生了什么。我有一个看起来像这样的函数:使用函数指针

#define cond int 
void Enqueue(cond (*cond_func)()); 

cond read() { 
return IsEmpty(some_global); // Returns a 1 or a 0 as an int 
} 

Enqueue(&read); 

但是,当运行上面的代码时,只要Enqueue被调用就会发生段错误。它甚至不执行任何内部函数。我运行了gdb,它只是在Enqueue被调用时显示它即将死亡 - 没有任何语句被处理。任何想法是怎么回事?任何帮助,将不胜感激。

+4

'#define cond int' < - 这是干什么用的?他们发明了'typedef'是有原因的。 – us2012

+1

命名你的函数'read'会导致可怕的问题。更好地避免它。 – wildplasser

+0

有人告诉我cond必须是布尔值,所以我只是把它作为int。 –

回答

0

你能给更多信息该代码因为根据我的解释代码工作正常。我已经尝试过 -

#define cond int 
void Enqueue(cond (*cond_func)()); 
cond read() 
{ 
int some_global=1; 
return IsEmpty(some_global); // Returns a 1 or a 0 as an int 
} 

int IsEmpty() 
{ 
return 1; 
} 

void Enqueue(cond (*cond_func)()) 
{ 
printf("Perfect"); 
return 0; 
} 

int main() 
{ 
Enqueue(&read); 
return 0; 
} 

它工作正常。

+1

'main()'和'IsEmpty()'应该有一个返回类型,它不再是二十世纪七十年代了。 –

+0

谢谢你指出我愚蠢的错误。:) –

0
#define cond int 

的意思是:

typedef int cond; 

虽然定义你的函数指针的别名可能是更合理的位置,例如:

typedef int (*FncPtr)(void); 

int read() { 
    printf("reading..."); 
} 

void foo(FncPtr f) { 
    (*f)(); 
} 

int main() { 
    foo(read); 
    return 0; 
} 
0

这工作得很好:

#include <stdio.h> 
#include <stdbool.h> 

typedef bool cond; 

void Enqueue(cond (*cond_func)(void)) { 
    printf("In Enqueue()...\n"); 
    cond status = cond_func(); 
    printf("In Enqueue, 'status' is %s\n", status ? "true" : "false"); 
} 

bool IsEmpty(const int n) { 
    return true; 
} 

cond my_cond_func(void) { 
    printf("In my_cond_func()...\n"); 
    return IsEmpty(1); 
} 

int main(void) { 
    Enqueue(my_cond_func); 
    return 0; 
} 

你的问题很可能是从别的地方来,比如你的Enqueue()定义,你不提供,或者你的函数被调用read()的事实,并与冲突这个名字更常见的功能。

+0

阅读缩短为了简洁的东西。我完全同意。 –