1. 函数头中的数组
一维:
int sum_arr(int *arr ,int n) 指针表示法
int sum_arr(int arr[], int n) 数组表示法
只有在函数头或者函数原型中,这两个表示函数的含义相同,都意味着arr是一个int型指针
二维:
arr[3][4]
int sum(int (*arr)[4], int size)
int sum(int arr[][4] ,int size) 注意括号必须有
注意这里不能使用const, arr本质上是指向指针的指针
此外,这里依旧是值传递,不过传递的是数组地址,所以在函数中对数组的修改是真实的
2. const 限定符与指针
表示符号常量,注意应在声明中就对const进行初始化
const type name = value (通常将name的首字母大写表示常量)
在指针中的使用
1) 指针指向一个常量对象——防止用指针修改所指向的值;
int age = 39;
const int* pt =$age; pt指向const int ,常量指针
本质上并不意味着pt指向的值是常量,只是对指针而言这个值是常量
故可以通过age变量来修改age的值,因为age并不是常量
一些探讨:
1)常规变量地址->常规指针 √
2)常规变量地址->指向const 的指针 √
3)const变量的地址->指向const的指针 √
const int a =9;
const int * pe = &a;
不能使用a和*pe来修改值
4)const变量的地址->常规指针 ×
否则可以使用指针来修改变量的值,很荒谬
5)非const指针 -> 指向const指针 仅限于一级间接关系(指针指向基本类型)可以 √×
int age =39;
int* pd = &age; 可以使用*pd=23修改但是pt的指向地址不变
const int* pt =pd;
若是两级的话,则指针的指针付给常量指针,可以通过原指针来修改const指针的指向(原地址的指针),荒谬
2)指针本身为常量——防止修改指针指向的位置
int age = 39;
const int* pt =$age; pt指向const int ,不能改指向的值,可以修改本身的值
int* const pd = &age; pd只能指向int,但可以改指向的值 ,指针常量
指针修饰的地址为常量
*pt pd ——const
pt *pd—— 不是const
3) 指向const对象的const指针
int age = 1;
const int* const pt = &age;
4) 总结:
将指针作为参数传递时,可以使用指向const的指针来保护数据,但要求只有一层间接关系(数据为基本类型),如果是指针或者指向指针的指针就不行
- 可以处理const和非const的数据,否则只能接受非 const数据
- 防止无意间修改数据
2.1 const用在函数前后的区别?
3. 函数与C-风格字符串
3.1 作为函数参数
1)char数组
2) 字符串字面值
3) 设置为字符串地址的char指针
char a[15]= " ";
char * str = "dafs";
int i = strlen(a);
int j = strlen(str);
int k=strlen("dasf");
若要进行遍历
while(*str){ 只要字符不为空值字符(\0)
...
str++;
}
3.2 作为返回值
函数无法返回字符串,但可以返回字符串的地址,注意必须使用new开辟内存,否则函数结束后内存就被释放掉了
char * dasf(char c, int n)
{
char* d = new char[n+1];
d[n] = '\0';
while(n-- >0)
d[n] = c;
return d;
}
在main()函数中记得使用delete