源自博文“[C++]数组的智能初始化”
http://blog.5d.cn/user3/z-star/200412/40139.html
数组的初始化在一般编程中经常会遇到:
1.可以用循环对每个元素进行初始化
2.利用C++的数组智能初始化:
2.1 只要用到{},默认初始化为0
2.2 否则不确定,随机。(这点类似于C++中的局部变量和静态变量)
3. C++ Standard Library提供了一个初始化的强力工具 memset
函数原型:
MSDN
void *memset( void *dest, int c, size_tcount );
dest 是目标起始地址, c 是要赋的值, count是要赋值的字节数
Required Header: <memory.h> or <string.h>
GNU
void *memset(void *s, int c, size_tn);
Required Header: <string.h>
Return Value:
return the value of 'dest' or 's'
no return value is reserved to indicate an error
memset的作用:初始化、重置 数组、结构体等内存空间。
特点:按字节拷贝,c will be converted to an unsigned char
注意:对于整型数组,只能初始化0(全0)或者-1(全1)
代码示例: #include <iostream> using namespace std; enum {array_size = 6}; void watch(const int *x) { for (int i = 0; i < array_size; i++) cout << " x[" << i << "] = " << x[i] ; cout << endl; } void main() { int a[array_size] = {0}; int b[array_size] = {1}; int c[array_size] = {1,2,3}; int d[array_size]; //the compiler may give a warning for //not initializing the array int e[array_size] = {}; watch(a); watch(b); watch(c); watch(d); watch(e); }
输出结果展示:
x[0] = 0 x[1] = 0 x[2] = 0 x[3] = 0 x[4] = 0 x[5] = 0 x[0] = 1 x[1] = 0 x[2] = 0 x[3] = 0 x[4] = 0 x[5] = 0 x[0] = 1 x[1] = 2 x[2] = 3 x[3] = 0 x[4] = 0 x[5] = 0 x[0] = 2008948808 x[1] = 37879496 x[2] = 2009050137 x[3] = 37879776 x[4] = 2009087664 x[5] = 2008948784 x[0] = 0 x[1] = 0 x[2] = 0 x[3] = 0 x[4] = 0 x[5] = 0
那么C++中的二维、多维数组又如何呢?
