forward declaration of a struct in C?

129,832

Solution 1

Try this

#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;
}

Solution 2

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

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

If you typedef your struct you can leave out the struct keyword.

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

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;
Share:
129,832
user1128265
Author by

user1128265

Updated on July 09, 2022

Comments

  • user1128265
    user1128265 almost 2 years
    #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;
    }
    

    I am missing something here. Please help me fix this. Thanks.

  • KANJICODER
    KANJICODER almost 5 years
    Nice! I use the last method you mentioned with slight variation: typedef struct context_s context; Is nice when you know you'll NEVER be using the token "context_s" but will be using "context".
  • sidcha
    sidcha over 4 years
    It would be clearer to just say what must be changed in the OP's code.