Question

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??

Was it helpful?

Solution

Inner struct p is not visible to the program outside the main function. Put your structure outside the main.
You are confused with the identical name of inner and outer struct p. You define the outer p as

typedef struct p *q;  

What does it mean? It means that you are defining a new type q which is a pointer to the struct p. But the problem is that there is no definition of struct p type is known here.
It is true that outer p is visible to main but inner p is not visible to outer p.

OTHER TIPS

struct p is defined inside main() and it is not visible to outside functions. you can solve compilation error by putting struct p outside of the main(global).

This is governed by C 2011 6.7.2.3 paragraphs 4 and 5:

4 All declarations of structure, union, or enumerated types that have the same scope and use the same tag declare the same type…

5 Two declarations of structure, union, or enumerated types which are in different scopes or use different tags declare distinct types.

Because typedef struct p *q; is outside of any function, it has file scope. Because struct p { int x; … } is inside main, it has scope inside main. Because these two declarations are in different scopes, they declare distinct types. Thus, the second declaration is not completing the first declaration of struct p; it is declaring a different struct p.

In turn, that means the type q is a pointer to the file-scope struct p and is not a pointer to the main-scope struct p. Because the file-scope struct p is incomplete, attempting to use it results in an error.

Maybe this illustrates things a little better:

#include <stdio.h>

struct foo {
    int a, b;
};

int main(void) {
    printf( "sizeof outer struct: %zu\n", sizeof(struct foo) );
    struct foo { int a; };
    printf( "sizeof inner struct: %zu\n", sizeof(struct foo) );
    return 0;
}

with the output (on my machine, but the exact values don't matter):

sizeof outer struct: 8
sizeof inner struct: 4

You're hiding the outer definition, similar to how you can hide variables.

HTH

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top