user9586643
user9586643

Reputation:

Error when initializing struct members in struct definition

I am trying to create a struct that has 2 pointers of type struct nodo defined above the code. But it gives me the error:

expected ':', ',', ';', '}' or 'attribute' before '=' token lista dati_mappa=NULL;".

Here is the code:

typedef int data;

struct nodo
{
    data elem;
    struct nodo *next;
};
typedef struct nodo *lista;

struct mappa {
    data R;
    data C;
    lista dati_mappa = NULL;
    lista pos_valida = NULL;
};

Upvotes: 0

Views: 101

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50912

You can't do that at declaration level in C (in C++ you can).

You need something like this:

...
int main()
{
  struct mappa mymap;
  mymap.dati_mappa = NULL;
  mymap.pos_valida = NULL;
  ...
}

or you can use aggragate initialization:

...
int main()
{
  struct mappa mymap = { .dati_mappa = NULL, 
                         .pos_valida = NULL };
  ...

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409482

You're not allowed to have inline initialization of structure members in C.

If you want to initialize members then you need to do it after you create instances of the structures.

Upvotes: 8

Related Questions