一重指针做函数参数
#include<iostream>
using namespace std;
void change(int *p)
{
*p = 20;
p++;
cout << p << endl;
}
int main() {
int a = 10;
int *pa = &a;
change(pa);
cout << pa << endl;
cout << a << endl;
system("pause");
return 0;
}
首先弄清楚,无论怎么改程序,&a的值永远不会变,可别智障了!
分析:
change(pa)传参时,指针p申请内存空间,p的内存空间中存的是pa(pa和a的地址的值相同),所以说此时传入函数的是指针的copy。因此,在函数内改变指针p的值并不会影响pa(即p++执行完后p和pa的值不可能相等)。
二重指针做函数参数
如果要修改pa,那么修改如下:
void change(int **p)
{
**p = 20;
(*p)++;
cout << *p << endl;
}
int main() {
int a = 10;
int *pa = &a;
change(&pa);
cout << pa << endl;
cout << a << endl;
system("pause");
return 0;
}
分析:
change(&pa)传参时,二重指针p申请内存空间,p的内存空间中存的是指针pa的地址,所以说此时传入函数的是指针的地址的copy。此时,(*p)就是pa,两者完全等价。所以在函数内执行(*p)++,pa的值自然也会随之改变。
一重指针的引用做函数参数
使用一重指针的引用做函数参数也修改pa(效果和二重指针做函数参数完全相同):
void change(int* &p)
{
*p = 20;
p++;
cout << p << endl;
}
int main() {
int a = 10;
int *pa = &a;
change(pa);
cout << pa << endl;
cout << a << endl;
system("pause");
return 0;
}
最后是一个实现二维数组动态分配的例子:
#include<iostream>
using namespace std;
int main()
{
int m,n;
cin >> m>>n;
int **a = new int*[m];
for (int i = 0; i < m; i++)
a[i] = new int[n];//a[i]的类型是int*
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = i + j;
cout << a[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < m; i++)
delete[] a[i];
delete[] a;
system("pause");
return 0;
}
#include<iostream>
using namespace std;
int main()
{
char*p[3] = { "America","China","Itlay" };//指针数组,数组中的每个元素都是char*类型的
char**q = p;
cout << q[0][0] << endl;
cout << q[1][0] << endl;
cout << q[2][0] << endl;
cout << q[0] << endl;
cout << q[1] << endl;
cout << q[2] << endl;
system("pause");
return 0;
}