gpt4 book ai didi

c - malloc() 中的双倍大小

转载 作者:行者123 更新时间:2023-11-30 20:01:31 25 4
gpt4 key购买 nike

如果我将 malloc() 中的大小加倍,内存分配是多少。

    struct node{
int data;
struct node*next;
};
void main(){
//What if I place 2,3 or 4 times the size.What is the memory allocation looks like.What if I do something like 1.5 times or say 1.3 times
struct node* a =(struct node *)malloc(2*sizeof(struct node));
//Moreover if I print this I get 8,if I am saying twice size,shouldn't I get 16 size(two nodes with 8 bytes each(4 byte of data and 4 byte of next))
printf("%d",sizeof(*a));
}

最佳答案

尽管您的问题不清楚,但我认为您对 sizeof() 感到困惑运算符,它不会为您提供对象的分配大小,而是为您提供其类型的大小,对于数组,因为它们是数组类型,所以它们的大小将是数组的大小(以字节为单位)。

这是标准草案的引用

6.5.3.4 The sizeof and _Alignof operators

  1. The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
  2. The _Alignof operator yields the alignment requirement of its operand type. The operand is not evaluated and the result is an integer constant. When applied to an array type, the result is the alignment requirement of the element type.
  3. When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. When applied to an operand that has array type, the result is the total number of bytes in the array. 103) When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.

此外,如果您使用 c 语言,请不要强制转换 void *对于其他指针类型,则不需要,如果是c++,则使用new而不是malloc() .

线路

node *a = malloc(2 * sizeof(*a));

分配足够的空间来容纳两个 node 类型的对象,所以如果你愿意的话,你可以使用它和索引符号

a[0].data = 1;
a[1].data = 2;

但这并不意味着 a是一个数组,这种语法是可能的,因为它相当于使用指针算术是

(*(a + 0)).data = 1;
(*(a + 1)).data = 1;
/* incrementa a by 1, and then dereference it -> a[1] */

我认为更容易看到 a不是数组。

<小时/>

103)当应用于声明为数组或函数类型的参数时,sizeof 运算符会生成调整后(指针)类型的大小(请参阅 6.9.1)。

关于c - malloc() 中的双倍大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31058192/

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