c - 在 C 中“声明为函数”

标签 c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LIMIT 100

/* Stack structure */
typedef struct stack
{
  char x[LIMIT][10];
  int top;
  void push(char *s);
  char *pop();
  void init();
  bool is_empty();
} stack;


/* Reset stack's top */
void stack init()
{
  this->top = 0;
}

代码继续但它给出了错误:

main.c|14|error: field 'init' declared as a function|

怎么了?从昨天开始我就想不通了。请帮助我。

最佳答案

C 中的结构不能有函数。但是,它们可以具有指向函数的指针。
您需要重新定义您的 struct stack

没有函数或指针的例子

struct stack {
    char x[LIMIT][10];
    int top;
};

void push(struct stack *self, char *s);
char *pop(struct stack *self);
void init(struct stack *self);
bool is_empty(struct stack *self);

函数指针示例

struct stack {
    char x[LIMIT][10];
    int top;
    void (*push)(struct stack *, char *);
    char *(*pop)(struct stack *self);
    void (*init)(struct stack *self);
    bool (*is_empty)(struct stack *self);
};

struct stack object;
object.push = push_function; // function defined elsewhere
object.pop = pop_function;   // function defined elsewhere
// ...

关于c - 在 C 中“声明为函数”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23329261/

相关文章:

c - "stack smashing detected"by getline & printf - 我真的不明白为什么

c++ stringstream到不同类型的变量

c - 只查找两个数组之间的第一个公共(public)元素

将字符串文字与字 rune 字连接起来

c - execve 的 arg 参数中是否可以进行命令注入(inject)

c - 在 C 中先于父执行子

c++ - 为什么 KCacheGrind 不显示我的函数名称?

c - 文件与数组,哪个更快?

从 +2147483648 到 -2147483648 可预测性的转换

c - 从 C 获取 Lua 字符串