-1

I have the following working code.

#include <stdlib.h>
#include <stdio.h>

typedef struct Mystruct {
    int id;
    struct Mystruct** mystructures;
} Mystruct;

int main () {
    Mystruct* ms1 = malloc(sizeof(Mystruct));
    ms1->id = 1;

    Mystruct* ms2 = malloc(sizeof(Mystruct));
    ms2->id = 2;

    Mystruct* ms3 = malloc(sizeof(Mystruct));
    ms3->id = 3;

    ms1->mystructures = malloc(sizeof(Mystruct) * 2);
    ms1->mystructures[0] = (struct Mystruct*)ms2;
    ms1->mystructures[1] = (struct Mystruct*)ms3;

    printf("%d\n", ms1->mystructures[0]->id);
}

I don't like having to use both Mystruct and (struct Mystruct) to refer to the same data type. Is there a way to use typedefined Mystruct recursively like in

typedef struct {
    int id;
    Mystruct** mystructures;
} Mystruct;

? This doesn't compile. Thanks

pistacchio
  • 56,889
  • 107
  • 278
  • 420
  • I do not like Marmite https://en.wikipedia.org/wiki/Marmite either. So not really a problem – Ed Heal Aug 02 '15 at 09:10
  • Well, I was about to post an answer when this was marked as duplicate. Anyway, there's a bug in your code here: `ms1->mystructures = malloc(sizeof(Mystruct) * 2);`. `mystructures` is of type `Mystruct **`, so you need to allocate space for `Mystruct *`. It should be `malloc(sizeof(Mystruct *) * 2);`. – Filipe Gonçalves Aug 02 '15 at 09:17
  • To avoid this kind of mistakes, I usually prefer (and recommend) to use `sizeof(*X)` when allocating space for `X`, this makes sure you always allocate the correct amount. So in this case you'd do `malloc(sizeof(*ms1->mystructures) * 2)`. – Filipe Gonçalves Aug 02 '15 at 09:18

2 Answers2

1

First define your typedef and then the struct:

typedef struct Mystruct Mystruct;

struct Mystruct {
    int id;
    Mystruct** mystructures;
} ;
this
  • 5,229
  • 1
  • 22
  • 51
1

You MUST use "struct Mystruct" only when defining the struct. Once you typedef it to "Mystruct" you can use "Mystruct" anywhere you want.

Mateo Hrastnik
  • 533
  • 1
  • 7
  • 20