用memset把int数组初始化为0是没问题的,但是要初始化成其他的数值,比如说-1或者别的什么数字,那就会报错,原因在于memset是以字节为单位进行填充的
详细的见百度百科https://baike.baidu.com/item/memset
其实想想也好理解,memset本来就是 < cstring >里面的函数,用处也主要是给char类型的字符串赋初值,用在int类型数组本来也就是不合理的用法。
那么我们要给int数组填充非0的元素怎么办呢?
我们要用到fill
函数,或者fill_n
函数,示例代码如下:
#include <iostream>
using namespace std;
int main()
{
int a[10];
fill(a,a+10,20);//三个参数,前面两个是地址,最后一个是填充值
for(int i = 0;i<10;i++)
cout <<a[i] << " " ;
cout << endl;
fill_n(a,5,-3);//三个参数,第一个是地址,第二个是个数,最后一个是填充值
for(int i = 0;i<10;i++)
cout <<a[i] << " " ;
cout << endl;
return 0;
}
用这两个函数可以给int数组初始化任何数值,反正比memset靠谱多了。
输出结果:
20 20 20 20 20 20 20 20 20 20
-3 -3 -3 -3 -3 20 20 20 20 20
欢迎交流,欢迎评论。
参考资料:
http://en.cppreference.com/w/cpp/algorithm/fill
http://en.cppreference.com/w/cpp/algorithm/fill_n