指针和二维数组

二维数组的本质就是连续的一维数组,元素在内存中是连续的。

一维数组名称:
    可以统计整个数组在内存中的长度
    可以获取整个数组在内存中的首地址
    int arr[5] = { 1,2,3,4,5 };    //arr 代表数组首元素的地址,数组的首地址, &arr代表整个数组的地址

二维数组做函数参数:二维数组其实就是一维数组,数据是连续存储
    实参,形参
    对于数组    int p[m][n]
    如果要取    p[i][j]的值    (i>=0 && i<m && 0<=j && j < n)
    编译器进行寻址    p + i * n + j   p代表首个元素的地址(首行地址,整个数组的地址,首个元素的地址是一样的)

二维数组demo

#include <iostream>

using namespace std;

void display(int (*arr)[4],int rows,int cools)
{

	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cools; j++)
		{
			cout << arr[i][j] << endl;
		}
	}
}

void display01(int arr[][4], int rows, int cools)
{

	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cools; j++)
		{
			cout << arr[i][j] << endl;
		}
	}
}

void display02(int **arr, int rows, int cools)
{

	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cools; j++)
		{
			//cout << arr[i][j] << endl;
			cout << *((int*)arr + i * cools + j) << endl;
		}
	}
}

void display03(int* arr, int rows, int cools)
{

	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cools; j++)
		{
			//cout << arr[i][j] << endl;
			cout << *(arr + i * cools + j) << endl;
		}
	}
}


int main()
{
	int arr[3][4] = { {2,4,5,8},{11,21,32,45},{78,67,54,44} };
	int rows = sizeof(arr) / sizeof(arr[0]);
	int cools = sizeof(arr[0]) / sizeof(arr[0][0]);
	//cout << "行: " << rows << endl;
	//cout << "列: " << cools << endl;

	//for (int i = 0; i < rows; i++)
	//{
	//	for (int j = 0; j < cools; j++)
	//	{
	//		cout << arr[i][j] << endl;
	//	}
	//}

	//display(arr,rows,cools);
	//display01(arr,rows,cools);
	//display02((int**)arr, rows, cools);
	display03((int*)arr, rows, cools);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值