2
typedef struct Stack_t* Stack;
typedef void* Element;
typedef Element (*CopyFunction)(Element);
typedef void (*FreeFunction)(Element);

你能解释一下第三行的含义吗?
谢谢

4

3 回答 3

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

有关函数指针,请参见此处

于 2013-04-23T13:31:21.717 回答
2

一个类似性质的例子来帮助你理解函数指针的 typedef。

typedef int (*intfunctionpointer_t) (int);

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

假设你有两个功能说,

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

然后,

intfunctionpointer_t function = foo;    
function(5);

调用 function(5),最终会调用 foo(5);

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

function = bar;
function(7);

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

于 2013-04-23T13:44:11.397 回答
1

这个:

typedef Element (*CopyFunction)(Element);

定义了一个为函数指针类型调用的别名CopyFunction,该函数返回一个 an 的实例,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(). */

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

于 2013-04-23T13:30:28.160 回答