先看下面的代码
#include "iostream"
using namespace std;
int main() {
int cards[4] = {1, 2, 3, 4};
int hand[4];
hand[4] = {2, 3, 4, 5};
hand = cards;
}
运行结果如下:
首先hand[4]表示的是数组的第5个元素(下标从0开始)而不是表示声明长度为4的数组, 另外c++也不允许如程序第八行那样给数组初始化(hand = cards)
再看下面这个例子
#include "iostream"
using namespace std;
int main() {
int cards[4] = {1, 2, 3, 4};
int hand[4];
//hand[4] = {2, 3, 4, 5};
//hand = cards;
float hotel[5] = {5.0, 2.5};
long totals[3] = {0};
short things[] = {1, 2, 3};
cout << "hotel[2], hotel[3], hotel[4] = " << hotel[2] << ", " << hotel[3] << ", " << hotel[4] << endl;
cout << "sizeof things = " << sizeof(things) << endl;
}
运行结果:
从运行结果可以看出来
float hotel[5] = {5.0, 2.5}; 这行代码声明了一个长度是5的float类型的数组名为hotel, 并且只初始化了前两个数据, 后三个默认都是0, 所以c++里可以使用类似long totals[3] = {0}这种方式对整个数组里的元素进行初始化
另外c++允许short things[] = {1, 2, 3}; 不明确声明数组的长度, c++编译器可以根据初始化时候传入的数值个数来自动确定数组的长度.
c++数组初始化的几种方法:
可以省略中间的"="
double score[3]{90.12, 99.99, 60.12};
大括号内可以不写任何东西, 表示所有数据均为0:
float nums[100]{};
数组初始化的时候不能把大的数据类型数据赋给小的数据类型的数组:
long num1[] = {1, 2, 3.0};
char num2[] {'a', 'b', 123123, '\0'};
char num3[] {'a', 'b', 123, '\0'};
上面三行代码第一行3.0是double而数组是long型的不合要求, 第二行因为123123的范围超出了char的范围不合要求, 第三行123是char能表示的数值, 所以没有问题