Подтвердить что ты не робот

Форвардная декларация структуры в C?

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(context *ctx);
  void (*func1)(void);
};

struct context{
    funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (context *ctx) { printf( "0\n" ); }

void getContext(context *con){
    con=?; // please fill this with a dummy example so that I can get this working. Thanks.
}

int main(int argc, char *argv[]){
 funcptrs funcs = { func0, func1 };
   context *c;
   getContext(c);
   c->fps.func0(c);
   getchar();
   return 0;
}

Мне что-то не хватает. Пожалуйста, помогите мне исправить это. Спасибо.

4b9b3361

Ответ 1

Попробуйте это

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

Ответ 2

Структура (без typedef) часто должна (или должна) быть связана с ключевым словом struct при использовании.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

Если вы напечатали свою структуру, вы можете оставить ключевое слово struct.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Обратите внимание, что законно повторно использовать имя структуры

Попробуйте изменить это объявление в своем коде следующим образом:

typedef struct context context;