How to set a Struct to NULL in C?

3

I want to check if there is any content in struct so I wanted to initialize the variables as NULL , because if they were equal to NULL would know that they were not created.

excerpts:

Struct:

struct  Fila
{

    int         capacidade;
    float       *dados;
    int         primeiro;
    int         ultimo;
    int         nItens;

};

startup:

struct  Fila
PPFila          =   (Fila)NULL,  <--- Erro de incompatibilidade
AUTFila         =   (Fila)NULL;  <--- Erro de incompatibilidade

Creation:

if(PPFila   ==  (Fila)NULL)
{

    //
    //  Cria as filas que gerencias as o envio das threads
    //
    criarFila(&PPFila,  20);
}

Does anyone have any tips how I can do this?

    
asked by anonymous 26.07.2016 / 20:08

3 answers

2

It is not possible to set a struct with NULL as it is declared.

Fila f = NUll;

error: invalid initializer.

If you want to assign NULL to a struct, you must declare it as a pointer:

Fila * PPFila = NULL,
     * AUTFila = NULL;
    
26.07.2016 / 20:44
2

stddef.h defines NULL as:

#define NULL ((void *)0)

So cast% from% to NULL , which is not even a type in this code, or assign Fila to a primitive type variable is "wrong". " NULL is not a value", it is an untyped pointer to address 0.

Use a pointer to your structure so you can initialize it as null.

struct Fila * PPFila = NULL;
    
26.07.2016 / 21:49
1

Well, for startup, what I like to do is to use memset to put all variables in ZERO.

Example:

struct  Fila PPFila, AUTFila;
memset(&PPFile, 0, sizeof(PPFila));
memset(&AUTFile, 0, sizeof(AUTFila));

To know if it is initialized or not, you can use some parameter of its structure that says this, or create a specific one to tell if it has already been initialized. In your case, it looks like the nItens field does exactly that. So, for verification:

if(PPFila.nItens == 0)
{
    //
    //  Cria as filas que gerencias as o envio das threads
    //
    criarFila(&PPFila,  20);
}
    
26.07.2016 / 20:25