如何确定总内存分配?

时间:2015-12-15 21:27:29

标签: 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. 的大小
  3. 2个语句malloc(sizeof(struct itmes));malloc(sizeof(*shop));

  4. 之间的区别是什么
  5. 这个宏返回的是什么?根据我的理解,将1添加到指针用于跳转到数组中的下一个元素,但我不明白这种情况。

1 个答案:

答案 0 :(得分:2)

  

1-分配了多少总内存?是否等于*shopstruct items

的大小

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

  

2-两个陈述malloc(sizeof(struct itmes));malloc(sizeof(*shop));

之间的区别是什么

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

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

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

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

  

当指针中添加或减去具有整数类型的表达式时,   result具有指针操作数的类型。如果指针操作数指向的元素   一个数组对象,并且该数组足够大,结果指向一个偏移的元素   原始元素使得结果和原始的下标不同   数组元素等于整数表达式。[....]