user3575963
user3575963

Reputation:

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

And codes go on but It gives that error:

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

What is wrong? I can not figure out it since yesterday. Please help me.

Upvotes: 8

Views: 9061

Answers (2)

phyrrus9
phyrrus9

Reputation: 1467

C cannot hold functions inside structs. But, you can place a function pointer.

void (*init)();

Upvotes: 3

pmg
pmg

Reputation: 108978

Structures, in C, cannot have functions. They can, however, have pointers to function.
You need to redefine your 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);

Example with function pointers

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

Upvotes: 13

Related Questions