gpt4 book ai didi

c - 如何确定总内存分配?

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:00 25 4
gpt4 key购买 nike

我通过一个 C 项目来理解一些概念并找到了以下代码。

#define MY_NODE_ALLOC(coffee) ((struct items *)(coffee) + 1)

struct store
{
char *name;
int id;
};

struct items
{
char *itemName
char *itemCode;
int quantity;
};

void * allocation(struct store *shop)
{
struct items *coffee = malloc(sizeof(struct items) + sizeof(*shop));
return MY_NODE_ALLOC(coffee);
}

我有以下问题

  1. 总共分配了多少内存?它是否等于 *shopstruct items 的大小?

  2. malloc(sizeof(struct itmes));malloc(sizeof(*shop)); 这两个语句有什么区别?

  3. 这个宏返回了什么?根据我的理解,指针加 1 用于跳转到数组中的下一个元素,但我不明白这种情况。

最佳答案

1- How much total memory is allocated ? is it equal to size of *shop and struct items ?

是的,以字节为单位的总大小,以防 malloc() 成功。

2- What is the difference between the 2 statements malloc(sizeof(struct itmes)); and malloc(sizeof(*shop));

在成功的情况下,两条语句分配不同数量的内存。

  • malloc(sizeof(struct itmes)); 分配与 struct itmes 大小相同的字节数(以字节为单位)。
  • malloc(sizeof(*shop); 分配与 *shop (struct store) 大小相同的字节数(以字节为单位)。

3- What is this macro returning ? As per my understanding adding 1 to pointer is used to jump to next element in array but i dont understand this case.

是的,你是对的。首先,他们将指针转换为 struct items * 类型,然后递增指针以指向下一个 struct items * 类型的内存地址。为了澄清,让我们引用 C11,第 6.5.6 章

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression.[....]

关于c - 如何确定总内存分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com