Why can't I check the sizeof a struct in C? (undeclared error)

Viewed 378

I am trying to figure out the sizeof(p) where p is the struct defined below; but, when I try and run the following code:

#include <stdio.h>

struct p
{
    char x;
    int y;
};

int main()
{
    printf("%d", sizeof(p));
    return 0;
}

I receive this error:

main.c: In function ‘main’:
main.c:19:25: error: ‘p’ undeclared (first use in this function)
     printf("%d", sizeof(p));
                         ^

I am a beginner in C and I tried to move p's definition into the main function, changing the definition of p, looking the error up online (none of the posts with the same error answered my question), etc., but I couldn't seem to get it to work. Any suggestions are appreciated.

1 Answers

In C (unlike in C++), the struct p... construct does not define a new type of variable. It only defines p as a particular type of struct. So, in order to get the size of that structure, or to declare a variable of that type, you need to use struct p to refer to it.

Like this:

#include <stdio.h>

struct p {
    char x;
    int y;
};

int main()
{
    printf("%zu\n", sizeof(struct p));
    // Alternatively ...
    struct p q;
    printf("%zu\n", sizeof(q));
    return 0;
}

Also, note that you should use the %zu format specifier for the size_t type.

Related