C: Typedef structure and pointers anomaly -
i on data structures classes , confused me.
it's related pointers properties guess, on research didn't find real explanation, idea why c allows this?
run-able code: http://ideone.com/kgh3lf
#include <stdio.h> #include <stdlib.h> /* declaring typedef struct */ typedef struct{ int a; char b[10]; }struct_one; /* declaring structure, intentional wrong calling of first structure */ struct struct_two{ int p; char q[10]; /* doesn't work expected... should be: struct_one var; */ // struct struct_one var; /* 1 work!!, , i'm not sure why */ struct struct_one *ptr; }; int main(void) { /* code */ return 0; }
you incorrectly assumed second structure "calls" first one. doesn't.
in reality first struct declaration declares untagged struct type typedef alias struct_one
. way refer type struct_one
. struct_one
, not struct struct_one
.
the second struct declaration declares struct struct_two
, refers type struct struct_one
. latter type has absolutely nothing declared type struct_one
: struct struct_one
, struct_one
2 different, unrelated types. reference struct struct_one
inside second struct seen introduction, declaration of new type struct struct_one
. compiler assumes define type later (if necessary).
since not doing else in code, not run problems caused such mistake. additional illustration of happen, see following example
int main(void) { struct_one *p = 0; struct struct_two s2; s2.ptr = p; return 0; }
this code produce diagnostic message compiler, because s2.ptr = p;
assignment illegal: pointer types unrelated. pointer of left hand side struct struct_one *
, pointer on right-hand side struct_one *
.
once again, in c language when use struct <something>
syntax in contexts not require complete type, can write virtually in place of <something>
: complete gibberish (as long lexically valid identifier). if type not yet known, compiler assume introducing new type, e.g.
int main() { struct klshcjkzdcdsamcbsj78q43698 *p = 0; }
the above valid c program.
Comments
Post a Comment