c - 指向结构的数组指针

标签 c arrays pointers structure

我写了这个程序:

#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/

相关文章:

c - 当符号等于零时运行时未定义的链接器符号

c - 随机化链表中的节点,C 程序

arrays - 在字典中添加键值对 swift

c - 在信号量(操作系统)中传递给 sem_init() 的参数的含义是什么?

c - 将 token 的内容放在引号中

c - 使用指针在递归函数中创建一个计数器?

c++ - 如何将一个类中指向另一个类的指针复制到 C++ 中的另一个指针?

C++:用于识别原始指针使用情况的统计信息

javascript - jQuery 计算 div 中的图像并根据 z-index 和 title attr 告诉我当前正在查看的图像

c - 类型为 void 的数组