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

标签 c pointers malloc

我通过一个 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/

相关文章:

c++ - AVL 树的不同节点中的键值可以相同吗?

c++ - 无法打开 UART。确保它没有被其他应用程序使用

c - 如何解决这个指针问题?

c - 类似 Getline 的函数崩溃

c++ - 在 Linux Qt Creator C++ 中对 char * 使用 malloc 时接收 SIGSEGV 信号

C 动态内存分配如何工作

c++ - 将两个库相互链接

c - 零大小的 memblocks 有什么用?

c++ - 动态指针和对象

c++ - 返回值会发生什么?