Data Structures (C)

2

Good morning.

I was working with the code of a program and I have a doubt about the data structures. We have these two cases, one in the "programa.c" and another in the "programa.h":

programa.c:

struct _estructura {
    /* El código aqui es indiferente */
};

programa.h:

typedef struct _estructura estructura;

I would like to know the difference in defining the structure directly in the program.c and the previous case. That is, in the .c we are declaring the structure and we define it in the .h? If someone could clarify it to me ...

Thank you very much, Greetings

    
asked by Ibai Carracedo 05.02.2018 в 10:27
source

1 answer

3

That is known as pre-declaración .

In the .h you are telling the compiler that the symbol struct _estructura is just that, a data structure; you do not indicate what it contains, you just tell it that it is a valid symbol, and that you know that it is declared completely elsewhere; that the compiler can trust you, that you know what you're doing.

On the other hand, in the .c you are fulfilling your word; you are telling the compiler what really is the struct struct _estructura .

Doing it this way, the compiler allows you to work with pointers to your struct _estructura . No allows you to work with the structure itself, only with pointers that reference it.

That's a common method of hiding the details to client programs ; If all  the functions that you use, in their arguments and / or in their return value, work exclusively with pointers, you can prevent anyone from touching the internal data of your struct _estructura : nobody knows them, not even the own compiler.

    
answered by 05.02.2018 / 10:35
source