定义指针变量
int *i = new int[5]; //初始化数组
int *j = new int(6); //初始化指向int变量的指针
int array[5] = {1, 2, 3, 4, 5};
int *a = array; //a 指向数组
int *b;
b = array; //b 指向数组
int e[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int arr[3]; //arr是包含3个int元素的数组
int (* arr )[3] = e; //初始化二维数组,arr是一个指向包含3个int元素的数组的指针变量
//初始化二维数组
int **k = new int *[3]; //初始化三个指向数组的指针
for(int i=0; i<3; i++) {
k[i] = new int[5]; //对上面初始化的指针初始化数组
}
for(int i=0; i<3; i++){
delete[] k[i];
}
int ** p_pointer;
int* p_int;
p_int = new int(3);
p_pointer = &p_int; //指向一个int类型的指针的指针
int ***p4;
p4 = &p_pointer; //指向一个int类型的指针的指针的指针
cout << p4 << endl;
cout << *p4 << endl;
cout << **p4 << endl;
cout << ***p4 << endl;
- 如何解释语句int (* arr )[3] = e ?
- *表示arr是一个指针,[3]表示是一个数组指针,int表示指针类型。
指针加/减
int *a = new int[2];
int c[5][2] = {{1,2},{3,4},{4,5},{5,6},{6,7}} ;
int (* b)[2] = c;
int *p;
p = a;
for(int i=0; i<2; i++){
a[i] = i;
}
for(int i=0; i<2; i++) {
cout<< a[i] <<endl;
}
cout << "len is : " << sizeof(a)/sizeof(a[0]) << endl;
cout << *(a+1) << endl;
cout << *a << endl;
cout << "access : " << *(*(b+2)+1) << endl;
cout << *(++p) << endl;
delete[] a;
返回的结果为
0
1
len is : 2
1
0
access : 5
1
函数指针与引用
#include<iostream>
using namespace std;
int f() { return 42;}
int main() {
int n=1;
int *pn = &n;
int &r = *pn;
int m = *pn;
cout << r << endl;
cout << m << endl;
int (*fp)() = &f;
int (&fr)() = *fp;
cout << fr() << endl;
cout << fp() << endl;
}
执行结果
➜ cplusplus_learn git:(zj) ✗ ./a.out
1
1
42
42
以上代码中的 int (&fr)() = *fp; 这个 &是引用。
引用,顾名思义是某一个变量或对象的别名,对引用的操作与对其所绑定的变量或对象的操作完全等价
语法:类型 &引用名=目标变量名;
结构体指针
#include<iostream>
using namespace std;
struct test{
string name;
int count;
};
int main() {
test a = {"zj", 4};
test *b = &a;
test *c = new test();
c->name = "oys";
c->count = 5;
cout << b->name << " " << (*b).count << endl;
cout << c->name << " " << (*c).count << endl;
}
执行结果
➜ cplusplus_learn git:(zj) ✗ ./a.out
zj 4
oys 5