如何使用默认值初始化动态数组? [英] How to initialise array dynamically with a default value?

查看:134
本文介绍了如何使用默认值初始化动态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初始化大小亿阵列(无符号短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 with 0,

The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

 calloc(number of elements, sizeof(type));

or you can also use memset() explicitly to initialize memory allocated by malloc() 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 than calloc()?

这篇关于如何使用默认值初始化动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆