[英]Why do we use malloc or calloc when we have a simpler code in c?
#include <stdio.h>
int main() {
int n = 0, i;
printf("Enter the size of array\n");
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++) {
a[i] = i + 1;
printf("%d,", a[i]);
}
}
May I know the difference between malloc()
and calloc()
and this code, because I guess both are fulfilling the need?我可以知道
malloc()
和calloc()
之间的区别以及这段代码,因为我猜两者都满足了需求?
Note that as per the latest standard, VLAs are not mandatory part of the spec.请注意,根据最新标准,VLA 不是规范的强制性部分。 Allocator functions (
malloc()
and family) are the standard way of allocating memory for which size is only known at run-time.分配器函数(
malloc()
和 family)是分配内存的标准方法,其大小仅在运行时才知道。
Quoting C18
, chapter 6.7.6.2/P4引用
C18
,第 6.7.6.2/P4 章
[...] (Variable length arrays are a conditional feature that implementations need not support; see 6.10.8.3.)
[...](可变长度数组是实现不需要支持的条件特性;参见 6.10.8.3。)
That said, there are other usage limitations in case of VLAs due to their nature, their lifetime is limited in the scope in which they are defined.也就是说,由于 VLA 的性质,在 VLA 的情况下还有其他使用限制,它们的生命周期在定义的范围内受到限制。 For example, you cannot return a VLA, defined in a function from a function call, but if you use allocator functions, you can return the pointer, as it's lifetime remains until programatically released (call
free()
).例如,您不能从函数调用返回在函数中定义的 VLA,但如果您使用分配器函数,则可以返回指针,因为它的生命周期一直保持到以编程方式释放(调用
free()
)。
The line线
int a[n];
declares a
as a variable-length array . a
a 声明为可变长度数组。 VLAs are useful, but limited: VLA 很有用,但有局限性:
static
keyword or at file scope;static
关键字或在文件范围内声明;int a[n] = {0};
int a[n] = {0};
; struct
or union
type;struct
或union
类型的成员; Like any auto
variable, they cease to exist when you exit their enclosing scope.与任何
auto
变量一样,当您退出其封闭范围时,它们将不复存在。
Dynamically-allocated memory has a few advantages over VLAs:动态分配的内存比 VLA 有几个优点:
free
it;free
它;malloc
, calloc
, and realloc
are supported by any hosted implementation;malloc
、 calloc
和realloc
; If all you need is some temporary working storage within a function, you don't know its size ahead of time, you don't need too much of it, and they are supported, then VLAs are a good option and less messy than using malloc
or calloc
.如果你只需要一个函数中的一些临时工作存储,你不知道它的大小,你不需要太多,并且它们是受支持的,那么 VLA 是一个不错的选择,并且比使用更简洁
malloc
或calloc
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.