简体   繁体   English

指向结构的数组指针

[英]array pointers to structures

I wrote this program: 我写了这个程序:

#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;
   }

Can you tell me how can inv[1].ID be set up to 20. When I allocated just 1 byte of memory for inv . 您能告诉我如何将inv[1].ID设置为20。当我为inv分配仅1个字节的内存时。 How can it carry data of multiple structures? 如何承载多种结构的数据?

There is undefined behaviour in your code - 您的代码中存在未定义的行为-

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

You allocate size equal to that of int and is not enough for structure and access unauthorized memory.And then the strcpy , you try to store more contents than the space available. 您分配的大小等于int大小,不足以用于结构化和访问未授权的内存。然后使用strcpy尝试存储比可用空间更多的内容。 name can contain 19 characters and '\\0' at end. name可以包含19字符,末尾可以包含'\\0' And the string you copy is larger then 19 characters. 并且您复制的字符串大于19字符。

Can you tell me how can inv[1].ID be set up to 20. When I allocated just 1 byte of memory for inv. 您能告诉我如何将inv [1] .ID设置为20。当我为inv分配的内存仅为1个字节时。 How can it carry data of multiple structures? 如何承载多种结构的数据?

TL;DR It cannot. TL; DR不能。

What you're seeing is invalid access of memory which invokes undefined behavior . 您看到的是对内存的无效访问,这将导致未定义的行为 There is nothing in C standard that prevents you from from writing a code accessing invalid memory, but as soon as you do that, voila!! C标准中没有什么可以阻止您编写代码来访问无效的内存,但是一旦这样做, 瞧!

The memory allocated to inv (by calling malloc(1) ) is way less then it should be. 分配给inv的内存(通过调用malloc(1) )要少得多 Thus, basically, you're trying to access memory that does not belong to you (your process) and hence that memory is invalid . 因此,基本上,您正在尝试访问不属于您的内存(您的进程),因此该内存无效 Any attempt to access invalid memory results in UB. 任何尝试访问无效内存的操作都会导致UB。

Following the same trail, even after you have allocated proper memory for inv , then also 遵循相同的方法,即使在为inv分配了适当的内存之后,也

 strcpy(inv[0].name,"hello charlie old mate");

will be UB, as you're trying to copy more than 20 elements into the destination having only size of 20 (which can hold 19 valid chars + 1 null terminator, if you want name to be used as a string ). 将为UB,因为您尝试将20元素复制到仅具有20个大小的目标中(如果您希望将name用作字符串 ,则可以容纳19个有效chars + 1个空终止 )。 Count your memory requirement properly and stay within bounds. 正确计算您的内存需求,并保持在界限之内。

That said, always check for the return value of malloc() for success before using the returned pointer. 也就是说,在使用返回的指针之前,请务必检查malloc()的返回值是否成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM