![](/img/trans.png)
[英]Why isn't sizeof for a struct equal to the sum of sizeof of each member?
[英]Why can't I check the sizeof a struct in C? (undeclared error)
我試圖找出sizeof(p)
其中p
是下面定義的struct
; 但是,當我嘗試運行以下代碼時:
#include <stdio.h>
struct p
{
char x;
int y;
};
int main()
{
printf("%d", sizeof(p));
return 0;
}
我收到此錯誤:
main.c: In function ‘main’:
main.c:19:25: error: ‘p’ undeclared (first use in this function)
printf("%d", sizeof(p));
^
我是 C 的初學者,我試圖將p
的定義移動到main
的 function 中,更改p
的定義,在線查找錯誤(沒有相同錯誤的帖子回答我的問題)等,但我似乎無法讓它工作。 任何建議表示贊賞。
在 C(與 C++ 中不同)中, struct p...
構造沒有定義新的變量類型。 它僅將p
定義為特定類型的struct
。 因此,為了獲得該結構的大小,或聲明該類型的變量,您需要使用struct p
來引用它。
像這樣:
#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;
}
另外,請注意您應該為size_t
類型使用%zu
格式說明符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.