[C++] Summary of several methods for pointer traversal of two-dimensional arrays

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

0. Preface

Simply record several methods of traversing two-dimensional arrays

1. Text

1.1 Method 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");
}

Insert picture description here

1.2 Method Two: Pointer

1.2.1 Write separately

#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 Combined Write

#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 Method Three: Pointer

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

Insert picture description here

references

[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

Guess you like

Origin blog.csdn.net/weixin_39190382/article/details/108111601