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;
};
5
  • 6
    Please note that it is very bad practice to hide pointers behind typedefs. Commented Dec 9, 2019 at 9: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 Commented Dec 9, 2019 at 9: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. Commented Dec 9, 2019 at 9:43
  • 2
    The typedef achieves nothing but hiding vital information for the programmer. This answer sums it up nicely. Commented Dec 9, 2019 at 9: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). Commented Dec 9, 2019 at 12:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.