我通过一个 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);
}
我有以下问题
总共分配了多少内存?它是否等于
*shop
和struct items
的大小?两条语句
>malloc(sizeof(struct itmes));
和malloc(sizeof(*shop));
之间有什么区别这个宏返回什么?根据我的理解,指针加 1 用于跳转到数组中的下一个元素,但我不明白这种情况。
最佳答案
1- How much total memory is allocated ? is it equal to size of
*shop
andstruct items
?
是的,总大小(以字节为单位),以防 malloc()
成功。
2- What is the difference between the 2 statements
malloc(sizeof(struct itmes));
andmalloc(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/