数组指针
#include<iostream>
using namespace std;
// 对数组进行操作会保存到实参中,本质指针传递
void myprint(int a[][4], int num_row)
{
for (int i = 0; i < num_row; i++) {
for (int j = 0; j < 4; j++) {
cout << a[i][j] << " ";
}
a[0][0]++;
cout << endl;
}
}
int main()
{
// 数组首地址a是常量,不能修改!!!
int a[3][4] = { {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}};
int b[2] = { 0, 1 };
myprint(a, 3);
cout << a[0][0] << endl;
int* p = a[0];
// 指针运算指向下一个元素的地址 包括+ - ++ --
cout << *p << ' ' << *(p + 1) << ' ' << *(p + 2) << ' ' << *(p + 3) << ' ' << endl;
// a[i] *(p+i) *(a+i) p[i]等效
cout << a[0][2] << ' ' << *(p + 2) << ' ' << *(a[0] + 2) << ' ' << p[2] << endl;
return 0;
}
函数指针
#include<iostream>
using namespace std;
// 函数指针: 返回值类型 (*函数指针名) (参数类型)
int res(int a, int b, int(*func)(int, int))
{
return func(a, b);
}
int max(int a, int b) {
return ((a > b)? a : b);
}
int min(int a, int b) {
return ((a > b) ? b : a);
}
int main()
{
cout << res(10, 100, &max) << endl;
cout << res(10, 100, &min) << endl;
return 0;
}
char指针
#include<iostream>
#include<string>
using namespace std;
int main()
{
// 只要常量指针指向相同的字符串常量,指向的地址相同,表示的值也相同
const char* x;
const char* y;
const char* z;
x = "china";
y = "china";
z = "China";
cout << (x == y) << endl;
cout << (x == z) << endl;
cout << (void*)x << endl;
cout << (void*)y << endl;
cout << (void*)z << endl;
cout << "-----------" << endl;
const char* e = "abc";
const char* f = "abc";
const char* g = "abb";
cout << (e == f) << endl;
cout << (e == g) << endl;
cout << (void*)e << endl;
cout << (void*)f << endl;
cout << (void*)g << endl;
cout << "-----------" << endl;
// 数组首地址不相同,与内容无关
char c[] = "abc";
char d[] = "abc";
char* q = c;
cout << (c == d) << endl;
cout << (c == q) << endl;
cout << (void*)d << endl;
cout << (void*)c << endl;
cout << (void*)q << endl;
return 0;
}
输出: