线性方式初始化二维数组,只需要利用/与%的关系即可。具体细节文章下面会有程序的流程分析
问题起源
想要用线性方式初始化二维数组
问题分析
例如a[3][4]
a[0][0] a[0][1] a[0][2] a[0][3]
a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]
如果线性方式初始化就用这样一个语句
a[i/4][i%4]
那么具体分析是
i = 0: 0/4 = 0 0%4=0
i = 1: 1/4 = 0 1%4=1
i = 2: 2/4 = 0 2%4=2
i = 3: 3/4 = 0 3%4=3
i = 4: 4/4 = 1 4%4=0
i = 5: 5/4 = 1 5%4=1
i = 6: 6/4 = 1 6%4=2
i = 7: 7/4 = 1 7%4=3
i = 8: 8/4 = 2 8%4=0
i = 9: 9/4 = 2 9%4=1
i = 10: 10/4 = 2 10%4=2
i = 11: 11/4 = 2 11%4=3
源码示例
#include<stdio.h>
#include<stdlib.h>
int main() {
int a[3][4];
for (int i = 0; i < 12; i++) {
a[i / 4][i % 4] = i;
printf("%d ", a[i / 4][i % 4]);
}
getchar();
}