数组指针与函数指针

数组指针

#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;
}

输出:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值