数组名是指针?——数组名就是数组这个变量的名字,数组跟指针都是 compund type,是独立的一个“类型”。

Define and Initialize

char a1[] = {'C', '+', '+'};       // list init, no null
char a2[] = {'C', '+', '+', '\0'}; // list init, explicit null
char a3[] = "C++";                 // null terminator added automatically
const char a4[3] = "C++";          // error: no space for the null!

Complicated Array Declarations

from right to left, from inside out.

int *ptrs[10];           // ptrs is an array of ten pointers
int &refs[10] = /* ? */  // error; reference is not object
int (*Parr)[10] = &arr;  // Parr is a pointer to an array of ten ints
int (&Rarr)[10] = arr;   // Rarr is a reference to …

说明数组名 arr 并不是一个指针,因为指向数组的指针不是 int** 而是 int (*)[10]. 并且声明引用时,也是直接拿数组名过来用。

Pointers and Arrays

when we use an array, the compiler ordinarily converts the array to a pointer to the first element. 🔗Type Conversions
Like when we subscript an array, we really subscript a pointer.
So…

Attention

No Copy or Assignment.

Guess when (is) assign(ed) to (by) array, we actually use it, so it convert to a pointer.

Mis Deduced by auto.

int a[] = {0, 1, 2};
auto pa(a);              // pa is an int* that point to the first element in a
decltype(a) b = {0, 1};  // b is an array with 0, 1, 0
 
auto &ra = a;            // ra is a reference to an array of 3 ints

记忆法:auto 我们经常 = 在用,这就是“use”,所以会转化为 pointer

⚠️ 最后一个 auto 还是按照原意使用了

Pointers are Iterators

🔗Pointer Arithmetic

Multidimensional Arrays

就是元素也为数组的数组。所以当我们 subscript 这个数组时,得到的是一个 inner-array。
使用多维数组的数组名时,会被转化为指向第一个 inner-array 的指针。

Using range for with Multi Arrays

int a[3][4] = {0};
for(auto &row : a){    // why ‘&’ is significant?
  for(auto col : row){
  	cout << col << endl;
  }
  cout << endl;
}

根据前面的知识我们知道:
拿数组直接 auto 会出指针,而指针并不是一个 sequence。所以为了防止这种情况,我们使用 reference 来避免,因为 reference 之后 refer to 一个数组,还是一个 sequence。

数组是一个实实在在的object

for(auto p = ia; p != ia + 3; ++p){
  for(auto q = *p; q!= *p + 4; ++q){
  	/* statements */
  }
}

如果不用 range for 来遍历数组,我们需要获得这个数组的 iterator,在这里就是一个简单的指针。

外层因为数组的特性,已经变为指向外层数组各个元素的指针。而因为多维数组的特性,指针指向的是内层数组。

内层同样需要内层的数组,因此 dereference 取得

Return a Pointer to Array

由于return就是赋值,所以我们不能直接return a array,所以我们一般借助reference和pointer

type ( *func(para_list) ) [dimen]

其实也蛮好理解的,因为 return 的效果和 init 一样,而我们 init 的就是 *func(para_list),所以结合定义数组指针的方法,得到了这条

Shortcuts by Alias

typedef int arr[10];
using arr = int[10];
arr* func();

Shortcuts by decltype

int arr[ ] = {1, 2, 3, 4, 5};
decltype(arr) *func();

再补充一嘴:为什么这里 decltype 可以,而 auto 不行呢?其实是因为 decltype 才会不把array convert to pointer

Shortcuts by auto

It’s called trailing return type. 其实是通用的,只是在复杂的type上会比较好用

auto func() -> int(*)[10];