我写了这个程序:
#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 = malloc(sizeof(1)); // you allocate size of int
inv[0].ID = 10;
strcpy(inv[0].name,"hello charlie old mate"); //copying more than your buffer can hold
您分配的大小等于 int
的大小,不足以用于结构和访问未经授权的内存。然后是 strcpy
,您尝试存储比空间更多的内容可用的。 name
可以包含 19
个字符和结尾的 '\0'
。并且您复制的字符串大于 19
个字符。
关于c - 指向结构的数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37284397/