int * const *, const int * const *, const int **

本文详细解析了C++中不同类型的指针概念及其使用场景,包括int*const*、constint*const*和constint**的区别,并通过示例代码演示了如何在实际编程中运用这些指针。
1. 必须先明确的概念:char const * 等价于 const char *

2. int * const * 能修改一级指针指向的内容(一级指针类型为int *),但不能改变一级指针。可以理解为(int *) const * 即 const (int *) * ,(类比char const * 即 const char *,不能改char;同理此处不能改int *,不过可以改int *指向的内容)

3. const int * const * 不能修改一级指针指向的内容(一级指针类型为const int *),不能改变一级指针,(const int *) const * 即 const (const int *) *, (类比char const * 即 const char *,不能改char;同理此处不能改const int *,自然不能改const int *指向的内容)

4. const int ** 可以理解为(const int *) * 指向const int * 的指针

5. 以上三者都不是类似char * const 情况(可以修改指向的内容,但是不能移动的指针)

#include <iostream>

void disp(const int * const * matrix, unsigned row, unsigned col)// int **可以转化成常量形式const int * const *
{
	for (size_t i = 0; i < row; i++)
	{
		for (size_t j = 0; j < col; j++)
		{
			std::cout << matrix[i][j] << "\t";
		}
		std::cout << std::endl;
	}
}

void modify(int * const * matrix, unsigned i, unsigned j, int value)
{
	matrix[i][j] = value;
}

int main()
{
	// 1.int * const *,const int * const *
	unsigned row = 4;
	unsigned col = 5;
	int ** matrix = (int **)malloc(sizeof(int *) * row);
	for (size_t i = 0; i < row; i++)
	{
		matrix[i] = (int *)malloc(sizeof(int) * col);
		for (size_t j = 0; j < col; j++)
		{
			static int t = 0;
			matrix[i][j] = ++t;
		}
	}
	disp(matrix, row, col);
	modify(matrix, 0, 0, -1);
	disp(matrix, row, col);
	for (size_t i = 0; i < row; i++)
	{
		free(matrix[i]);
	}
	free(matrix);

	// 2.const int ** ,上面动态开辟的二维数组明显不是这种类型的
	const int num = 5;
	const int * pnum = #
	const int ** ppnum = &pnum;
	std::cout << **ppnum << std::endl;

	system("pause");
	return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值