[英]How does structure allocate memory?
我試圖找出結構變量的大小。 按照代碼sizeof結構應該是28,但是結果顯示是8,name給出了20多個字符,但是打印的很好。 我無法理解這種行為,有人可以幫助我嗎?
我正在使用 DevC++ 編譯我的 C 代碼。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct
{
char name[20];
int identity;
int number;
}S;
int main()
{
S *s=(S *)malloc(sizeof(S));
printf("Size of structure is %d \n",sizeof(s));
strcpy(s->name,"abcdefghijklmnopqrstuvwxyzffjfjfzdabcdefg");
printf("name is %s and size of name is: %d\n", s->name ,sizeof(s->name));
s->identity=10;
s->number=20;
printf("Identity is %d and size of identity is %d\n",s->identity, sizeof(s->identity));
printf("Number is %d and size of number is %d\n",s->number , sizeof(s->number));
return 0;
}
我希望“結構大小”的輸出為 28,但實際輸出為 8。
s
沒有類型S
。 它的類型為S *
,即它是一個指針,因此sizeof(s)
是系統上結構指針的大小。
如果要打印結構的大小,則需要打印sizeof(S)
或sizeof(*s)
。
此外,您使用了錯誤的格式說明符來打印sizeof
的結果。 您當前在每個printf
調用中都使用%d
,而正確的格式說明符是%zu
用於sizeof
。
這是我的觀察,首先在這里
S *s=(S *)malloc(sizeof(S));
內存分配給s
,它是結構S
的指針,打印sizeof(s)
不會導致整個結構的大小,它只是打印結構指針的大小。
如果要打印完整結構的大小,請使用sizeof(S)
或sizeof(*s)
。
其次,使用%d
格式說明符打印sizeof()
運算符結果會導致未定義行為。 使用%zu
。 例如
printf("Size of structure is %zu \n",sizeof(*s));
也在這里
strcpy(s->name,"abcdefghijklmnopqrstuvwxyzffjfjfzdabcdefg");
s->name
只能包含20
字符,包括終止\\0
字符和復制超過size
字符會導致未定義的行為。 由於C
不執行數組邊界檢查,並不意味着應該編寫訪問邊界數據的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.