1. 当且仅当用于函数头或函数原型中时,int* array和int array[]含义才是相同的。都意味着array是一个int型指针。一般当指针指向数组的第一个元素时,用数组表示法,而指向一个独立值时,用指针表示法。
2. array[i] = *(array + i):表示数组第i个元素的值
&array[i] = array + i:表示数组第i个元素的地址。
3. 数组作为参数:实际并没有传递数组的内容,而是将数组的地址,元素种类,元素个数传递给函数。(常规变量传递的是copy,数组时,由于是地址,所以是原来的数组而不是copy)
4. 根据数据的存储方式和使用方式来定义数据的类型。
5. 指向常量的指针:const int* pt = &a; *pt为const,即无法使用指针修改*pt的值;但是pt可以其他地址;
区分指针本身是常量:int* const pt = &a; * const pt为常量指针,所以pt不能指向其他地址,但是*pt可以修改。
6. C++禁止cost地址赋给非const指针。
7. 函数定义时,参数尽量使用const:避免数据被无意间修改引发bug;const可以接收const和非const参数。如果不加const只能接收非const参数。
1 8 #include9 using namespace std; 10 11 int sumArray(const int array[], int size); //如果指向的是数组的第一个元素,则用这个形式更直观 12 int sumPointer(const int* aPointer, int size); //如果指向的是一个独立的值,则使用这个形式更直观 13 int sumArrayPointer(const int* begin, const int* end); //通过传递两个指针来指定数组区间:数组区间传递 14 15 int main() 16 { 17 int score[5] = {60, 90, 100, 98, 99}; 18 cout << "sizeof score = " << sizeof(score) << endl; 19 int totalScore = sumArray(score, sizeof(score) / sizeof(int)); 20 cout << "totalScore = " << totalScore << endl; 21 22 int total = sumPointer(score, sizeof(score) / sizeof(int)); 23 cout << "total = " << total << endl; 24 25 int totalAP = sumArrayPointer(score, score + sizeof(score) / sizeof(int)); 26 cout << "totalAP =" << totalAP << endl; 27 } 28 29 int sumArray(const int array[], int sizeofArray) 30 { 31 int total = 0; 32 for (int i = 0; i < sizeofArray; i++) 33 { 34 total += array[i]; 35 } 36 return total; 37 } 38 39 int sumPointer(const int* aPointer, int size) 40 { 41 int total = 0; 42 for(int i =0; i < size; i++) 43 { 44 total += aPointer[i]; 45 } 46 return total; 47 } 48 49 int sumArrayPointer(const int* begin, const int* end) 50 { 51 const int* pt; 52 int total = 0; 53 for(pt = begin; pt !=end; pt++) 54 { 55 total += *pt; 56 } 57 return total; 58 } 59
函数无法返回字符串,但是可以返回字符串的地址。这样做更加高效。
结构体变量的行为更接近于基本变量:按值传递,可以互相赋值,取地址使用&。
如需要多个字符串,可以声明一个string对象数组,而不是char二维数组。
传递引用可以解决效率低和书写形式复杂的问题。
函数指针:函数名,函数在内存开始的地址。
一定要区分传递的是函数的地址还是函数的返回值。
typedef定义类型的别名更加灵活。



