简体   繁体   English

为什么我不能检查 C 中结构的大小? (未声明的错误)

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

I am trying to figure out the sizeof(p) where p is the struct defined below;我试图找出sizeof(p)其中p是下面定义的struct 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.我是 C 的初学者,我试图将p的定义移动到main的 function 中,更改p的定义,在线查找错误(没有相同错误的帖子回答我的问题)等,但我似乎无法让它工作。 Any suggestions are appreciated.任何建议表示赞赏。

In C (unlike in C++), the struct p... construct does not define a new type of variable.在 C(与 C++ 中不同)中, struct p...构造没有定义新的变量类型。 It only defines p as a particular type of struct .它仅将p定义为特定类型的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.因此,为了获得该结构的大小,或声明该类型的变量,您需要使用struct p来引用它。

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.另外,请注意您应该为size_t类型使用%zu格式说明符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM