剑指offer-0x03

这里写图片描述

#include <iostream>

using namespace std;


bool Find(int* matrix, int rows, int columns, int numbers)
{
    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] == numbers)
            {
                found = true;
                break;
            }
            if(matrix[row*columns+column]>numbers)
                column--;
            else
                row ++;
            //column --;
        }
    }
    return found;
}

int main()
{
    int matrix[4][4]= {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
    bool result = Find(matrix,4,4,7);
    cout << "Hello world!" <<result<< endl;
    return 0;
}
E:CodeBlocksFindInPartiallySortedMatrixmain.cpp|34|error: cannot convert 'int (*)[4]' to 'int*' for argument '1' to 'bool Find(int*, int, int, int)'|

参数传递出错,传递二维数组方式不对。

void fun(double *);//申明
main()
{
double n[2][5]={1,2,3,4,5,6,7,8,9,0};
fun(n);
}
void fun(double *p)//接受n这个地址
{
……
}
出错
我想传指针,不要n[][5]这种形式,因为这个函数要作用于任意尺寸的二维数组
void fun(double *p, int s, int t)//  s行t列二维数组
{
    函数里面的n[i][j]用p[i *t + j]替代
}
调用格式:
fun(&n[0][0], 2, 5);
其实就是利用二维数组行序优先来计算元素位置

改为:

bool result = Find(&matrix[0][0],4,4,7);

Hello world!1

Process returned 0 (0x0) execution time : 0.000 s
Press any key to continue.

keep calm and carry on
原文地址:https://www.cnblogs.com/geekvc/p/6657323.html