【笔记】 C++中 Multidimentional Arrays 的 initialization(初始值)

对于 Multidimentional Arrays 的 initialization 比较多样,我认为最简单的方法即为记住以下几种特殊情况,再由特殊到一般,做到“举一隅而以三反隅”。
以下是试验程序:

#include <iostream>
using namespace std;

int main()
{
    
    
	int a1[3][4];
	for (int i = 0; i != 3; i++)
		for (int j = 0; j != 4; j++)
			cout << a1[i][j] << " ";
	cout << endl;

	int a2[3][4] = {
    
     0 };
	for (int i = 0; i != 3; i++)
		for (int j = 0; j != 4; j++)
			cout << a2[i][j] << " ";
	cout << endl;

	int a3[3][4] = {
    
     {
    
    0} };
	for (int i = 0; i != 3; i++)
		for (int j = 0; j != 4; j++)
			cout << a3[i][j] << " ";
	cout << endl;

	int a4[3][4] = {
    
     {
    
    0},{
    
    4} };
	for (int i = 0; i != 3; i++)
		for (int j = 0; j != 4; j++)
			cout << a4[i][j] << " ";
	cout << endl;

	int a5[3][4] = {
    
     {
    
    0},{
    
    4},{
    
    8} };
	for (int i = 0; i != 3; i++)
		for (int j = 0; j != 4; j++)
			cout << a5[i][j] << " ";
	cout << endl;

	int a6[3][4] = {
    
     0,3,6,9 };
	for (int i = 0; i != 3; i++)
		for (int j = 0; j != 4; j++)
			cout << a6[i][j] << " ";
	cout << endl;

	return 0;
}

Result:

-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 4 0 0 0 0 0 0 0
0 0 0 0 4 0 0 0 8 0 0 0
0 3 6 9 0 0 0 0 0 0 0 0


【C++ Primer(5th Edition) Exercise】练习程序 - Chapter3(第三章)

猜你喜欢

转载自blog.csdn.net/weixin_50012998/article/details/108196501
今日推荐