我寫了這個程序:數組指針結構
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct inventory{
int ID;
char name[20];
int value;
};
int main()
{
struct inventory *inv;
inv = malloc(sizeof(1));
inv[0].ID = 10;
strcpy(inv[0].name,"hello charlie old mate");
inv[0].value = 20;
inv[1].ID = 20;
printf("%d", inv[1].ID);
return 0;
}
你能告訴我怎樣才能inv[1].ID
被設置爲20.當我爲inv
僅配置了1個存儲字節。它如何攜帶多個結構的數據?
你有沒有聽說過*未定義的行爲*? – haccks
「當我爲inv分配一個字節的內存時」是錯誤的。代碼分配給'sizeof(1)'字節,當然不是1,但更可能是4. – chux
只是爲了詳細說明@chux sir所說的,'sizeof'考慮的是數據類型,而不是_value_,文字'1'是類型'int'。 :) –