目录
C++中的二维数组
一、二维数组的定义
1、数据类型 数组名[ 行数 ][ 列数 ];
//1、数据类型 数组名[ 行数 ][ 列数 ];
int arr[2][3];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
cout << arr[0][0] << endl;
cout << arr[0][1] << endl;
cout << arr[0][2] << endl;
cout << arr[1][0] << endl;
cout << arr[1][1] << endl;
cout << arr[1][2] << endl;
//外层循环打印行数,内层循环打印列数
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr[i][j] << endl;
}
}
2、数据类型 数组名[ 行数 ][ 列数 ] = {{数据1,数据2},{数据3,数据4}};
//2、数据类型 数组名[ 行数 ][ 列数 ] = {{数据1,数据2},{数据3,数据4}};
int arr2[2][3] =
{
{1,2,3},
{4,5,6}
};
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr2[i][j]<<" ";
}
cout << endl;
}
3、数据类型 数组名[ 行数 ][ 列数 ] = {数据1,数据2,数据3,数据4};
3、数据类型 数组名[ 行数 ][ 列数 ] = {数据1,数据2,数据3,数据4};
int arr3[2][3] = { 1,2,3,4,5,6 };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr3[i][j] << " ";
}
cout << endl;
}
4、数据类型 数组名[ ][ 列数 ] = {数据1,数据2,数据3,数据4};
int arr4[][3] = { 1,2,3,4,5,6 };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr4[i][j] << " ";
}
cout << endl;
}
二、二维数组的数组名
1、可以查看占用内存空间大小;
#include<iostream>
using namespace std;
int main()
{
//二维数组名称用途
//1、可以查看占用内存空间大小
int arr[2][3] =
{
{1,2,3},
{4,5,6}
};
cout << "二维数组占用内存空间为:" << sizeof(arr) << endl;
cout << "二维数组第一行占用内存空间为:" << sizeof(arr[0]) << endl;
cout << "二维数组第一个元素占用内存空间为:" << sizeof(arr[0][0]) << endl;
cout << "二维数组行数为:" << sizeof(arr) / sizeof(arr[0]) << endl;
cout << "二维数组列数为:" << sizeof(arr[0])/sizeof(arr[0][0]) << endl;
system("pause");
return 0;
}
2、可以查看二维数组的首地址。
#include<iostream>
using namespace std;
int main()
{
//二维数组名称用途
//2、可以查看二维数组的首地址
cout << "二维数组的首地址为:" << (int)arr << endl;
cout << "二维数组第一行首地址为:" << (int)arr[0] << endl;
cout << "二维数组第一行首地址为:" << (int)arr[1] << endl;
cout << "二维数组第一个元素首地址为:" << (int)&arr[0][0] << endl;
cout << "二维数组第一个元素首地址为:" << (int)&arr[0][1] << endl;
system("pause");
return 0;
}
三、二维数组案例——考试成绩统计
#include<iostream>
using namespace std;
#include<string>
int main()
{
//二维数组案例-考试成绩统计
//1、创建二维数组
int scores[3][3] =
{
{100,100,100},
{90,50,100},
{60,70,80}
};
string name[3] = { "张三","李四","王五" };
//2、统计每个人的总分数
for (int i = 0; i < 3; i++)
{
int sum = 0;
for (int j = 0; j < 3; j++)
{
sum += scores[i][j];
cout << scores[i][j] << " ";
}
cout <<name[i]<<"的总分为" <<sum << endl;
}
system("pause");
return 0;
}