C Primer Plus学习笔记 —— Ch10 数组与指针

1、当使用数组名称作为参数传递给函数时,若函数意图不是改变数组内容,而仅仅是为了使用数组内数据,那么为了防止对数组指针的误操作,应该在声明函数与定义函数时在声明数组类型前加关键字const,这样当函数错误的试图修改数组内容时,编译器会捕捉这种错误。

e.g.   

         int sum_of(const int [], int n);        /* declare const */
         int sum_of(const int arr[], int n)
        {
            int i, sum;
            sum = 0;
            for(i = 0; i < n; i++)
                sum += arr[i];
            return sum;
        }

2、使用const声明指针,const所保护的内容不是指针本身,而是指针所指向的内容,而指针本身是可以改变的。

e.g.

int num[] = {1, 2, 3, 4};
const int *ptr;
ptr = num;
*ptr = 10; /* error, read-only */
ptr++; /* change the pointer itself is permitted */

3、使用const可以对指针添加更多约束,如声明不可改变指向位置的指针,如使用两个const声明既不可改变所指向位置又不可改变所指向内容的指针。关键在于const所在位置。

e.g.

int num[4] = {1, 2, 3, 4};
int rate[2] = {5, 6};
int * const ptr = num;
ptr = rate; /* not permitted */
*ptr = 10;  /* no problem */

const int * const ptr2 = rate;
ptr2 ++; /* not permitted */
*ptr2 = 4; /* not permitted */

11、声明一个指向二维数组的指针

e.g.

int num[3][2] = {{1,2}, {3, 4}, {5, 6}};
int (* ptr)[2]; /* declare format */
ptr = num;
prt[1][0] = 100;

12、复合字面量(compound literal)的意义以及用作数组初始化。字面量是除符号常量外的常量,如5是Int型的字面量,3.3是double型的字面量, 'Y'是char型的字面量。复合字面量带有数组的结构信息,一般用作数组初始化,省去了新建数组的麻烦。

e.g.

int (* pt)[4]; /* 声明二维数组指针pt */
pt = (int [][4]){{1, 2, 3, 4}, {5, 6, 7, 8}}; /* 直接对数组初始化,不必新建数组再给指针赋值 */

猜你喜欢

转载自blog.csdn.net/l1120101214/article/details/81038605
今日推荐