2013-04-23 122 views
2
typedef struct Stack_t* Stack; 
typedef void* Element; 
typedef Element (*CopyFunction)(Element); 
typedef void (*FreeFunction)(Element); 

你能解释一下第三行的含义吗?
感谢c中的实现通用堆栈

回答

2

一个类似的性质的例子,以帮助您理解,函数指针的typedef。

typedef int (*intfunctionpointer_t) (int); 

,所以我们在这里说的是什么,intfunctionpointer_t是一种类型的函数指针,函数int类型的单个参数,并返回一个整数。

假设你有两个功能说,

int foo (int); 
int bar (int); 

然后,

intfunctionpointer_t function = foo;  
function(5); 

调用函数(5),最终会调用foo(5);

您也可以通过将相同的函数指针分配给同一个签名的另一个函数来扩展它。

function = bar; 
function(7); 

现在调用函数(7),最终会调用bar(7);

1

此:

typedef Element (*CopyFunction)(Element); 

定义的别名称为CopyFunction一个函数指针类型,用函数返回一个Element的实例,并具有Element一个参数。

人为的例子:

/* Function declaration. */ 
Element f1(Element e); 
Element f2(Element e); 

Element e = { /* ... */ }; 
CopyFunction cf = f1; 
cf(e); /* Invokes f1(). */ 

cf = f2; 
cf(e); /* Invokes f2(). */ 

的函数指针使用其他例如:

3

这是一个function pointer你可以解决一个函数来取一个Element并返回一个Element,像

Element ReturnElem(Element el){ } //define function 

CopyFunction = ReturnElem; //assign to function pointer 

Element el = ....; 
Element el2 = CopyFunction(el); //call function using function-pointer 

参见here为函数指针。