二维数组基本知识
1、二维数组的定义:类型 数组名[行号][列号]eg:int arr[3][4]2、二维数组的初始化整体赋值只能在定义的时刻进行eg:int arr[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}} 3行4列int arr[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12},13}错误,初始值给太多,因为设置的只有3行int arr[3]
1、二维数组的定义:类型 数组名[行号][列号]
eg:int arr[3][4]
2、二维数组的初始化
整体赋值只能在定义的时刻进行
eg:int arr[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}} 3行4列
int arr[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12},13} 错误,初始值给太多,因为设置的只有3行
int arr[3][4]={1,2,3,4,5,6,7,8,9,10,11,12} 也可以表示3行4列
1 2 3 4
5 6 7 8
9 10 11 12
int arr[3][4]={{1,2,3,4},{5,6},{9,10}} ,表示:
1 2 3 4
5 6 0 0
9 10 0 0
int arr[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12}} ,代表3行4列,默认行优先
int arr[3][]={1,2,3,4,5,6,7,8,9,10,11,12} ;错误,只告诉行,不告诉列不能使用
int arr[][4]={1,2,3,4,5,6,7,8,9,10,11,12} ;因为行优先 ,所以可以省略行号
int arr[][4]={1,2,3,4,5,6,7,8,9,10},二维指针为:
1 2 3 4
5 6 7 8
9 10 0 0
3、修改二维数组的值:
arr[1][2]=100 表示将二维数组arr[][]第2行第3列的值赋值为100
4、二维数组 的应用,将一个2*3矩阵转置变成3*2矩阵
#include <stdio.h>
int main()
{
int arr[3][4] = { 1,2,3,4,5,6,7,8,9,10,11,12 };
int brr[4][3] = {};
for (int i = 0; i < 3;i++)
{
for (int j = 0; j < 4; j++)
{
brr[j][i] = arr[i][j];
}
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ", brr[i][j]);
}
printf("\n");
}
}
5、
void fun(int arr[3][4],int low)
{
for (int i = 0; i <low; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[3][4] = { 1,2,3,4,5,6,7,8,9,10,11,12 };
int low = sizeof(arr) / sizeof(arr[0]);//计算行数
fun(arr,low);
}
二维数组传参时,行参数会损失,列不会
6、有一个3*4的矩阵,求出最大的元素,和其对应的行号和列号
法1:
int main()
{
int arr[3][4] = { 12,23,3,4,56,62,7,81,89,10,11,12 };
int max = 0;
int max_i = 0;
int max_j = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
if (arr[i][j] > max)
{
max = arr[i][j];
max_i = i;
max_j = j;
}
}
}
printf("%d %d %d\n", max, max_i, max_j);
}
法2:
void fun1(int arr[3][4],int low)
{
int max = arr[0][0];
int c = 0;
int d = 0;
for (int i = 0; i <low; i++)
{
for (int j = 0; j < 4; j++)
{
if (arr[i][j] > max)
{
max= arr[i][j];
c = i;
d = j;
}
}
}
printf("%d %d\n", c, d);
}
int main()
{
int arr[3][4] = { 12,23,3,4,56,62,7,81,89,10,11,12 };
int low = sizeof(arr) / sizeof(arr[0]);//计算行数
fun1(arr,low);
}
更多推荐
所有评论(0)