我编写了以下 C99 代码并且想知道结构声明。在其中我声明了两个函数指针,它们最终指向主代码中的两个 push/pop 方法。在函数指针声明中,我省略了参数,程序编译正常。它是否正确?我确定我已经读过必须提供参数。这是正确的 C99 行为吗?
#include <stdio.h>
#define INITIAL_STACK_SIZE 1000
typedef struct stack
{
int index;
void *stack[INITIAL_STACK_SIZE];
void* (*Pop)(); //<-- Is this correct?
void (*Push)(); //<-- Is this correct?
} stack;
stack CreateStack(void);
void PushStack(stack*, void *);
void *PopStack(stack*);
stack CreateStack(void)
{
stack s = {0, '\0'};
s.Pop = PopStack;
s.Push = PushStack;
return s;
}
void PushStack(stack *s, void *value)
{
if(s->index < INITIAL_STACK_SIZE)
{
s->stack[s->index++] = value;
}
else
{
fputs("ERROR: Stack Overflow!\n", stderr);
}
}
void *PopStack(stack *s)
{
if(s->index > 0)
{
return s->stack[--s->index];
}
else
{
fputs("ERROR: Stack Empty!\n", stderr);
return NULL;
}
}
int main(int argc, char *argv[])
{
stack s = CreateStack();
s.Push(&s, "Hello");
s.Push(&s, "World");
printf("%s\n", (char*)s.Pop(&s));
printf("%s\n", (char*)s.Pop(&s));
return 0;
}
我尝试将参数添加到函数指针,但我得到一个编译器错误,Extraneous old-style parameter list.
所以我猜它是正确的,但会喜欢另一种意见。
编辑:我遇到了上述'Extraneous old-style parameter list'错误,因为我使用typedef名称'stack'而不是使用带有'stack'的struct关键字来定义它是我当前定义的结构。
我正在使用Pelles C编译器。