【C++】指针遍历二维数组若干种方法小结

every blog every motto: You will never know unless you try

0. 前言

简单记录几种遍历二维数组的方法

1. 正文

1.1 方法一:

#include<iostream>
using namespace std;

// 定义常量
const int ROW = 3; // 数组的行数
const int COLUMN = 5; // 数组的列数
void test123()
{
    
    
	// 生成数组
	int arr[3][5] = {
    
    
		{
    
     0,1,1,0,1 },
		{
    
     0,0,1,0,1 },
		{
    
     0,0,1,0,1 }
	};

	int *p;
	p = arr[0];

	for (int row=0; row < ROW; row++)
	{
    
    
		for (int column=0; column < COLUMN ;column++)
		{
    
    
			cout << arr[i][j] << " "; // 关键部分
		}
		cout << endl;
	}

}

int main()
{
    
    

	test123();

	system("pause");
}

在这里插入图片描述

1.2 方法二:指针

1.2.1 分开写

#include<iostream>
using namespace std;

// 定义常量
const int ROW = 3; // 数组的行数
const int COLUMN = 5; // 数组的列数
void t2()
{
    
    
	// 生成数组
	int arr[3][5] = {
    
    
		{
    
     0,1,1,0,1 },
		{
    
     0,0,1,0,1 },
		{
    
     0,0,1,0,1 }
	};

	int *p;
	p = arr[0];

	for (int row=0; row < ROW; row++)
	{
    
    
		for (int column=0; column < COLUMN ;column++)
		{
    
    
			
			cout << *p << " "; // 关键部分
			p++; // 关键部分
		}
		cout << endl;
	}

}

int main()
{
    
    

	t2();

	system("pause");
}

1.2.2 合并写

#include<iostream>
using namespace std;

// 定义常量
const int ROW = 3; // 数组的行数
const int COLUMN = 5; // 数组的列数
void t2()
{
    
    
	// 生成数组
	int arr[3][5] = {
    
    
		{
    
     0,1,1,0,1 },
		{
    
     0,0,1,0,1 },
		{
    
     0,0,1,0,1 }
	};

	int *p;
	p = arr[0];

	for (int row=0; row < ROW; row++)
	{
    
    
		for (int column=0; column < COLUMN ;column++)
		{
    
    
			
			cout << *p++ << " "; // 关键部分
		}
		cout << endl;
	}

}

int main()
{
    
    

	t2();

	system("pause");
}

1.3 方法三:指针

#include<iostream>
using namespace std;

// 定义常量
const int ROW = 3; // 数组的行数
const int COLUMN = 5; // 数组的列数
void test123()
{
    
    
	// 生成数组
	int arr[3][5] = {
    
    
		{
    
     0,1,1,0,1 },
		{
    
     0,0,1,0,1 },
		{
    
     0,0,1,0,1 }
	};

	int *p;
	p = arr[0];

	for (int row=0; row < ROW; row++)
	{
    
    
		for (int column=0; column < COLUMN ;column++)
		{
    
    
			cout << p[row*COLUMN+column] << " "; // 关键部分
		}
		cout << endl;
	}

}

int main()
{
    
    

	test123();

	system("pause");
}

在这里插入图片描述

参考文献

[1] https://blog.csdn.net/qq_42384665/article/details/103985558?utm_medium=distribute.pc_relevant_right.none-task-blog-BlogCommendFromBaidu-7.channel_param_right&depth_1-utm_source=distribute.pc_relevant_right.none-task-blog-BlogCommendFromBaidu-7.channel_param_right

猜你喜欢

转载自blog.csdn.net/weixin_39190382/article/details/108111601