0

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;
};
klutt
  • 30,332
  • 17
  • 55
  • 95
  • 6
    Please note that it is very bad practice to hide pointers behind typedefs. – Lundin Dec 09 '19 at 09:25
  • @Lundin hi, I have just started to learn. Could you point some situations which this practice would lead to errors and problems in the code It woudl really helpl me to understand why shouldn't I use it this way or in what situations I should. It would really help me. Thanks –  Dec 09 '19 at 09:35
  • 2
    Lets say you want to dynamically allocate an instance of `struct nodo`, then you need to use the `sizeof` operator to get the size of the structure. If you hide the structure behind a type-alias one commonly use that type-alias as the argument to the `sizeof` operator. And if that type-alias is a pointer, then you allocate the size of a pointer, and not the whole structure. `sizeof(struct nodo) != sizeof(lista)`. Such errors are unfortunately very easy to do. – Some programmer dude Dec 09 '19 at 09:43
  • 2
    The typedef achieves nothing but hiding vital information for the programmer. [This answer](https://stackoverflow.com/a/43312230/584518) sums it up nicely. – Lundin Dec 09 '19 at 09:44
  • It is not very bad practice to hide pointers behind type definitions. Note that the answer alleged to sum it up nicely is a minority view by a large margin (currently 11 votes compared to 101 for the leading answer). – Eric Postpischil Dec 09 '19 at 12:29

2 Answers2

8

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

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 };
  ...
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115