'declared as function' in 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 top */
void stack init()
{
  this->top = 0;
}

And the codes continue, but it gives this error:

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

What's wrong? I can’t figure it out from yesterday. Please help me.

+4
source share
2 answers

Structures in C cannot have functions. However, they may have pointers to functioning.
You need to override struct stack.

Example without functions or pointers

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);

Function Pointer Example

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
// ...
+7
source

C cannot contain functions inside structures. But you can put a pointer to a function.

void (*init)();
+2
source

Source: https://habr.com/ru/post/1538319/


All Articles