C++ 数组的初始化方法详解,数据名内涵为数组这种数据结构,在arrayTest函数体内,str是数组名,那为什么sizeof的结果却是指针的长度?这是因为:
(1)数组名作为函数形参时,在函数体内,其失去了本身的内涵,仅仅只是一个指针;
(2)很遗憾,在失去其内涵的同时,它还失去了其常量特性,可以作自增、自减等操作,可以被修改。
先看数组初始化
#include <iostream>
using std::cout;
using std::endl;#include <iomanip>
using std::setw;int main()
{
int n[ 10 ];for ( int i = 0; i < 10; i++ )
n[ i ] = 0;for ( int j = 0; j < 10; j++ )
cout << n[ j ] << endl;return 0;
}输出结果
0
0
0
0
0
0
0
0
0
0
初始化一个数组
#include <iostream>
using std::cout;
using std::endl;#include <iomanip>
using std::setw;int main()
{
int n[ 10 ] = { 2, 7, 4, 8, 5, 4, 9, 7, 6, 3 };
for ( int i = 0; i < 10; i++ )
cout << n[ i ] << endl;return 0;
}
静态数组将被初始化为0
#include <iostream>
using std::cout;
using std::endl;void staticArrayInit( void );
void automaticArrayInit( void );int main()
{
staticArrayInit();
automaticArrayInit();staticArrayInit();
automaticArrayInit();
return 0;
}void staticArrayInit( void )
{
static int array1[ 3 ];for ( int i = 0; i < 3; i++ )
cout << "array1[" << i << "] = " << array1[ i ] << " ";for ( int j = 0; j < 3; j++ )
array1[ j ] = 0;
}void automaticArrayInit( void )
{
int array2[ 3 ] = { 1, 2, 3 };for ( int i = 0; i < 3; i++ )
cout << "array2[" << i << "] = " << array2[ i ] << " ";for ( int j = 0; j < 3; j++ )
array2[ j ] = 0;
}
结果
array1[0] = 0 array1[1] = 0 array1[2] = 0 array2[0] = 1 array2[1] = 2 array
2[2] = 3 array1[0] = 0 array1[1] = 0 array1[2] = 0 array2[0] = 1 array2[1]
= 2 array2[2] = 3