malajedala
malajedala

Reputation: 907

Recursive structure definition in C, error "forward declaration"

I want do declare my structure as a recursive one. So what I did until now looks like this:

 typedef struct {

 char *string;
 struct my_struct **children; //I want a list of children, therefore pointer to pointer
 int child_num;
 } my_struct;

But when I then try to initialize it like this:

my_struct *alig;
alig = malloc(sizeof(my_struct)*1);
alig->child_num = 5;
alig->string = malloc(sizeof(char)*9);
strncpy(alig->string, "AAACGTCA", 8);

alig->children = malloc(sizeof(my_struct*)*alig->child_num);

int j;
for (j = 0; j < alig->child_num; j++) {
    alig->children[j] = malloc(sizeof(my_struct)*1);
    alig->children[j]->string = malloc(sizeof(char)*9); // *********error ********
}

I get the error: "./structurs.h:27:13: note: forward declaration of 'struct my_struct' "

As well as this error at the marked line: main.c:56:22: error: incomplete definition of type 'struct my_struct'

Does someone now where my mistake is??

Upvotes: 0

Views: 175

Answers (3)

Gopi
Gopi

Reputation: 19874

 typedef struct {

 char *string;
 struct my_struct **children; //I want a list of children, therefore pointer to pointer
 int child_num;
 } my_struct;

should be

 typedef struct my_struct{

 char *string;
 struct my_struct **children; //I want a list of children, therefore pointer to pointer
 int child_num;
 } my_struct;

As said by @iharob there is no struct my_struct in your code and compiler is complaining about it you first have a struct my_struct has shown and then have a typedef for your struct

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134366

In your code

typedef struct {
 char *string;
 struct my_struct **children; 
 int child_num;
 } my_struct;

does not define a struct called struct my_struct, rather , it typedefs my_struct to be an alias of an unnamed struct. So you cannot use struct my_struct in your code. Either

Either

  • You need to put the typedef before the structure definiion.

or

  • You need to use a named struct.

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

There is no struct my_struct in your code, your struct is an anonymous typedef, you need it to be like this

typedef struct my_struct {
     char *string;
     struct my_struct **children;
     int child_num;
} my_struct;

Or even

typedef struct my_struct my_struct;
struct my_struct {
     char *string;
     my_struct **children;
     int child_num;
};

Upvotes: 6

Related Questions