1.数组的定义
// both buf_size and max_files are const const unsigned buf_size = 512, max_files = 20; int staff_size = 27; // nonconst const unsigned sz = get_size(); // const value not known until run time char input_buffer[buf_size]; // ok: const variable string fileTable[max_files + 1]; // ok: constant expression double salaries[staff_size]; // error: non const variable int test_scores[get_size()]; // error: non const expression int vals[sz]; // error: size not known until run time
注意点:
- 数组的维数必须是const的,对于这一点很诧异,第二条语句居然不通过,而第5条则可以,不知道编译器是怎么搞的
- 维数声明在变量后面,c#则在前面
2.显示初始化({})
const unsigned array_size = 3;int ia[array_size] = {0, 1, 2};
3.特殊的字符数组
由于字符串非常常用,所以特殊一些
char ca1[] = { 'C', '+', '+'}; // no null char ca2[] = { 'C', '+', '+', '\0'}; // explicit null char ca3[] = "C++"; // null terminator added automatically
注意:
- ca2和ca3是相同的,维数为4(注意数组不要超界) const char ch3[6] = "Daniel"; // error: Daniel is 7 elements
- 数组不可直接复制和赋值的
int ia[] = {0, 1, 2}; // ok: array of intsint ia2[](ia); // error: cannot initialize one array with anotherint main(){ const unsigned array_size = 3; int ia3[array_size]; // ok: but elements are uninitialized! ia3 = ia; // error: cannot assign one array to another return 0;}
4.数组下标访问
可用size_t来访问数组元素,而非数值
const size_t array_size = 10;int ia[array_size]; // 10 ints, elements are uninitialized// loop through array, assigning value of its index to each elementfor (size_t ix = 0; ix != array_size; ++ix) ia[ix] = ix;
数组是很多数据结构的基础,长度不可变,较为底层,可用c++标准库中的一些高级数据结构来简化数组的操作