【发布时间】:2016-05-17 19:08:33
【问题描述】:
我写了这个程序:
#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 字节的内存时。它如何承载多种结构的数据?
【问题讨论】:
-
你听说过未定义的行为吗?
-
“当我只为 inv 分配 1 个字节的内存时。”是错误的。分配的代码
sizeof(1)字节肯定不是 1,但更可能是 4。 -
只是为了详细说明@chux sir 所说的,
sizeof考虑的是数据类型,而不是 值,文字1的类型是int。 :) -
“我支付了一个停车位,但后来我在那个停车位和一些相邻的停车位上停了很多车。怎么可能?我只付了一个停车位。”
-
@ThomasPadron-McCarthy 让我知道你明天早上是否能在那里找到你的车。 :)
标签: c arrays pointers structure