二维数组元素的赋初值
赋初值一般形式:
int s[2][4]={
{7,8,9,7},
{5,4,1,9},
}
不提倡的形式:
int s[2][3]={1,2,3,4,5,6};
int s[ ][3]={1,2,3,4,5,6};
错误的赋值形式:
int s[2][ ]={1,2,3,4,5,6};
> 对于数组来说只允许左边第一个[ ]内的数是可以省略的。形参也是如此。
二维数组的引用和遍历
仔细研读下面算法——了解二维数组的引用和遍历
/*
题目: 把各上下对齐的两个数加起来并输出
7 9 8 7
4 3 5 7
*/
/* 二维数组元素的引用和遍历
题目: 把各上下对齐的两个数加起来并输出
7 9 8 7
4 3 5 7
*/
#include<stdio.h>
void shuchu(const int [],const int );
void jia(const int a[][4],const int ,const int ,int []);
int main()
{
int jiashu[2][4]= //存放加数
{
{7,9,8,7},
{4,3,5,7},
};
int he[4]; //存放和
//需要两个数给出数组维度
jia(jiashu,sizeof jiashu /sizeof jiashu[0],sizeof jiashu[0] /sizeof jiashu[0][0],he);
shuchu(he,sizeof he /sizeof he[0]);
return 0;
}
void jia(const int a[][4],const int hs,const int ls,int he[])
//数组、 行数、列数、和
{
int i;
for(i=0;i<ls;i++)
{
int j;
for(he[i]=0,j=0;j<hs;j++) //i 是列, j 是行
he[i]+=a[j][i]; //特别注意a 的两个下表不要弄反
}
}
//输出
void shuchu(const int a[],const int n)
{
int i;
for(i=0;i<n;i++)
printf("%d"" ",a[i]);
}