二维数组_一维数组

二维数组在内存中占据连续的空间。在内存中从上到下存储各行元素,在同一行中按照从左到右的顺序存储。

因此可以根据行号和列号计算出相对于数组首地址的偏移量,从而找到对应元素。

eg.      int *matrix    rows行columns列   matrix[ row * columns + column]

二维数组转化为一位数组:

#include <iostream>

using namespace std;

void display(int* matrix)
{
  cout << matrix[4] << endl;    //代表二维数组a的第二行,第一个元素
}

int main()
{
    int a[2][3];
    for(int i = 1; i <= 2; ++i)
        for(int j = 1; j <= 3; ++j)
        {
            a[i-1][j-1] = i+j;
            cout << a[i-1][j-1] << " ";
            if(j % 3 == 0)
                cout << endl;
        }
    display(a[0]);     //将二维数组第一行的首地址(即二维数组首地址)传入

    cout << "Hello World!" << endl;
    return 0;
}

 

posted @ 2016-10-05 16:06  Lunais  阅读(359)  评论(0编辑  收藏  举报