如何使用默认值初始化动态数组? [英] How to initialise array dynamically with a default value?
问题描述
我是初始化大小亿阵列(无符号短INT)用C 4.3.2和大小1000000的另外两个int数组但同时在线法官submiting,它被赋予的 SIGSEGV 错误。
为此,我决定用默认值0动态初始化我的数组,由循环增值需要较长的时间。
我的问题是如何使用的默认值动态初始化数组?
您可以使用的 无效*释放calloc(为size_t nmemb个,为size_t大小);
功能与 0
的
释放calloc()
函数分配内存nmemb个
元素的数组
大小字节每返回一个指针分配的内存。
的内存设置为零
。如果nmemb个
或大小0
,那么释放calloc()
返回或者NULL
,或唯一指针值以后可以
已成功传递到免费()
。
块引用>释放calloc(元素数目,sizeof的(类型));
或者你也可以使用
memset的()
明确初始化通过分配的内存的malloc()
电话。注意:
释放calloc()
不是魔术要么 - 它同时使用循环的地方,以取代垃圾全部用0。参见: 为什么
的malloc()
+memset的()
比释放calloc()
?较慢>I was initializing array (unsigned short int) of size 100000000 in C 4.3.2 , and other two int array of size 1000000. But while submiting on Online judge, it was giving SIGSEGV error .
Therefor i decided to initialize my array dynamically with a default value 0, as adding value by loop takes much time.
My question is how to initialise array dynamically with a default value ?
解决方案You can use
void *calloc(size_t nmemb, size_t size);
function to initialize memory with0
,The
calloc()
function allocates memory for an array ofnmemb
elements of size bytes each and returns a pointer to the allocated memory. The memory is set tozero
. Ifnmemb
or size is0
, thencalloc()
returns eitherNULL
, or a unique pointer value that can later be successfully passed tofree()
.
calloc(number of elements, sizeof(type));
or you can also use
memset()
explicitly to initialize memory allocated bymalloc()
call.Note:
calloc()
isn't magic either - it will also use a loop somewhere to replace the garbage with all zeroes.See also: Why
malloc()
+memset()
is slower thancalloc()
?这篇关于如何使用默认值初始化动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!