[英]The offset of each field and the size of the following structure declarations
A. struct P1 {short i; int c; int *j; short *d;};
struct P1 {short i; int c; int *j; short *d;};
D. struct P4 {char w[16]; int *c[2]};
struct P4 {char w[16]; int *c[2]};
E. struct P5 {struct P4 a[2]; struct P1 t};
struct P5 {struct P4 a[2]; struct P1 t};
答案說P1的總大小是16個字節。 但我認為短路需要4個(插入2個字節以滿足對齊要求),int需要4個,兩個指針* j和* d每個需要8個。所以總大小應該是4 + 4 + 8 + 8 = 24。搞錯了? 此外,對於E. P5,t的偏移是24.我不知道它是怎么來的。 a [2]是一個包含兩個元素的數組。 每個元素都是P4結構。 既然P4的大小是32,那么[2]不應該占用64個字節?
每個字段的偏移量和以下結構聲明的大小
填充,對齊和整數大小有很多問題會影響結果。 最好使用標准代碼報告偏移值和大小。
所以總大小應該是4 + 4 + 8 + 8 = 24.我弄錯了嗎?
合理的計算,但不是確定的。 大小取決於編譯器和平台的對齊,填充。 即使對於已知的體系結構,結果也可能因編譯器及其選項而異。
既然P4的大小是32,那么[2]不應該占用64個字節?
與先前的問題一樣,許多考慮因素都在起作用。
要查找struct
成員的偏移量,請使用offsetof()
要查找struct
的大小,請使用sizeof()
。
要打印這些值,請使用正確的匹配打印說明符: "%zu"
使用正確的語法。 審查使用;
在P4
和P5
。
struct P1 {
short i;
int c;
int *j;
short *d;
};
struct P4 {
char w[16];
int *c[2];
};
struct P5 {
struct P4 a[2];
struct P1 t;
};
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("PI i:%zu\n", offsetof(struct P1, i));
printf("PI c:%zu\n", offsetof(struct P1, c));
printf("PI j:%zu\n", offsetof(struct P1, j));
printf("PI d:%zu\n", offsetof(struct P1, d));
printf("PI size:%zu\n\n", sizeof(struct P1));
printf("P4 w:%zu\n", offsetof(struct P4, w));
printf("P4 c:%zu\n", offsetof(struct P4, c));
printf("P4 size:%zu\n\n", sizeof(struct P4));
printf("P5 a:%zu\n", offsetof(struct P5, a));
printf("P5 t:%zu\n", offsetof(struct P5, t));
printf("P5 size:%zu\n\n", sizeof(struct P5));
}
輸出:您的輸出可能會有所不同
PI i:0
PI c:4
PI j:8
PI d:12
PI size:16
P4 w:0
P4 c:16
P4 size:24
P5 a:0
P5 t:48
P5 size:64
有一種簡單的方法可以找到解決方案:編寫代碼並運行它。
#include <stdio.h>
typedef struct P1 {
short i;
int c;
int* j;
short* d;
} P1_t;
typedef struct P2 {
char w[16];
int* c[2];
} P4_t;
typedef struct P5 {
P4_t a[2];
P1_t t;
} P5_t;
int main() {
P1_t a;
P4_t b;
P5_t c;
printf("%d %d %d\n", sizeof(a), sizeof(b), sizeof(c));
return 0;
}
但是,由於原始類型和指針(如int
和short*
未鏈接到特定大小,因此結果可能因平台而異。 我在Windows子系統Linux上運行它,我的輸出是:
$ 24 32 88
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.