【发布时间】:2016-07-04 08:45:28
【问题描述】:
如果我在函数中有一个指针并且我知道它的大小,那么在初始化指针时使用malloc 会更好吗?
例如,
如果我有一个功能,这样做会更好吗
int * func(int size){
int * ptr = (int *) malloc(size);
//some code
return ptr;
}
或者这个
int * func(int size){
int * ptr;
ptr = (int *) malloc(size);
//some code
return ptr;
}
【问题讨论】:
-
我会使用
int * ptr = malloc(sizeof *ptr * size);我想知道您的代码的size是否考虑到sizeof(int)。 -
请定义“更好”这个词。
-
第二个不是初始化器,而是(初始)赋值。
-
@Olaf 在 C 中,对于标量类型,
T a = b;被定义为与T a; a = b;相同,所以这不是一个大问题。 -
@M.M:请记住,其他初学者会阅读这篇文章,他们认为这可以用于数组和
structs 等复合类型。
标签: c function malloc dynamic-memory-allocation coding-efficiency