Why can I use a typedef of a type that does not exist?

The following small program compiles gcc and works fine:

#include <stdio.h> #include <stdlib.h> typedef struct foo dne; int main(int argc, char *argv[]) { dne *dne_var = malloc(sizeof(void*)); printf("%p\n", dne_var); return 0; } 

Why is typedef really valid?

+5
source share
1 answer

Line

 typedef struct foo dne; 

implicitly declares a struct (incomplete at this point) struct foo structure. A pointer to an incomplete type is a full type, for example, its size is known, and you can declare an object of this type. However, struct foo not complete until you provide its full declaration, for example,

 dne dne_var; 

or dereferencing your pointer to access structure fields will be invalid.

+10
source

Source: https://habr.com/ru/post/1200862/


All Articles