Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I use a typedef of a type that doesn't exist?

Tags:

c

The following small program compiles on gcc and runs 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 the typedef valid?

like image 783
Chaosed0 Avatar asked Aug 21 '14 17:08

Chaosed0


1 Answers

The line

typedef struct foo dne;

implicitly declares an (incomplete at this point) structure struct foo. A pointer to an incomplete type is a complete type, so e.g. it’s size is known and you can declare an object of that type. However, struct foo itself isn’t complete until you provide a full declaration of it, so e.g.

dne dne_var;

or dereferencing your pointer to access the fields of the structure would be invalid.

like image 145
mafso Avatar answered Sep 28 '22 19:09

mafso