二维数组名和指针

 

#include <iostream>
using namespace std;

#define M 2
#define N 3

int main()
{
    int a[M][N] = {1,2,3,4,5,4}; 
    cout<<&(a[0])<<endl;    //00DCFA64
    cout<<&(a[0])+1<<endl;  //00DCFA70,offest:12
    cout<<a<<endl;          //00DCFA64,a=&(a[0]),
    cout<<a+1<<endl;        //00DCFA64

    cout<<&(a[0][0])<<endl;   //00DCFA64
    cout<<&(a[0][0])+1<<endl; //00DCFA68,offest:4
    
    int* ptr = (int*)(a);  //ptr=&(a[0][0])
    cout<<ptr<<endl;       //00DCFA64

    //for(int i = 0; i < sizeof(a)/sizeof(int); i++)
    //{
    //    if((*ptr++) == 4)
    //    {
    //        cout << "i=" << i/N << ", j=" << i%N << endl;
    //    }
    //}
    return 0;
}

&a[0]、&a[0][0]的值是相等的,但意义不同(对编译器来说),因为a[0] 保存的是一个指向一个具有3个元素的整型数组,而&a[0]则是获取这个数组的地址, 同样对于a[0][0]来说,a[0][0]是a[0]数组中的第一个数据,也就是一个整数,&a[0][0]则是这个整数的地址,因此在指针操作上结果不同。

理解上,变量a是一个具有2个元素的数组,这2个元素是一个具有3个元素的整型数组。  

int a[M][N] = {1,2,3,4,5,4};  写成 int a[M][N] = {{1,2,3},{4,5,4}};  更容易理解。

数组名a=&a[0] 

另外,二维数组在内存中占据连续的空间,在内存中从上到下存储各行元素,在同一行中按照从左到右的顺序存储。因此,可以考虑定义一个指针 int* ptr = (int*)(a); ,更方便地访问二维数组的元素。

#include <iostream>
using namespace std;

// 二维数组matrix中,每一行都从左到右递增排序,
// 每一列都从上到下递增排序
//判断一个整数是否在该二维数组中
bool Find(int* matrix, int rows, int columns, int number)
{
    bool found = false;

    if(matrix != NULL && rows > 0 && columns > 0)
    {
        int row = 0;
        int column = columns - 1;
        while(row < rows && column >=0)
        {
            if(matrix[row * columns + column] == number)
            {
                found = true;
                break;
            }
            else if(matrix[row * columns + column] > number)
                -- column;
            else
                ++ row;
        }
    }

    return found;
}

 上例中,在给函数Find()传递参数时,要用(int*)matrix,而不能直接使用二维数组名matrix。

注意数组内元素的索引方式。

posted on 2015-10-18 16:04  conard  阅读(201)  评论(0编辑  收藏  举报