typedef struct p *q;
int main()
{
struct p
{
int x;
char y;
q ptr;
};
struct p p = {1, 2, &p};
printf("%d\n", p.ptr->x);
return 0;
}
The above program throws the following compilation error:
1.c:24: error: dereferencing pointer to incomplete type
However, If I move the typedef
inside main func
OR if i move structure definition outside main, there is no compilation error.
Can anyone explain why is it happening??
Inner
struct p
is not visible to the program outside themain
function. Put your structure outside themain
.You are confused with the identical name of inner and outer struct
p
. You define the outerp
asWhat does it mean? It means that you are defining a new type
q
which is a pointer to the structp
. But the problem is that there is no definition ofstruct p
type is known here.It is true that outer
p
is visible tomain
but innerp
is not visible to outerp
.