gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:17:49 26 4
gpt4 key购买 nike

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com