查漏补缺,为2020年春季面试做准备。

问题1:二维数组,如何作为参数传递

问题2:二维数组,如何申请内存空间

问题3:二维数组,申请内存之后,如何释放的。

#include <iostream>
using namespace std;
/*传二维数组*/

//第1种方式:传数组,第二维必须标明
/*void display(int arr[][4])*/
void display1(int arr[][4],const int irows)
{
    for (int i=0;i<irows;++i)
    {
        for(int j=0;j<4;++j)
        {
            cout<<arr[i][j]<<" ";     //可以采用parr[i][j]
        }
        cout<<endl;
    }
    cout<<endl;
}
//第2种方式:一重指针,传数组指针,第二维必须标明
/*void display(int (*parr)[4])*/
void display2(int (*parr)[4],const int irows)
{
    for (int i=0;i<irows;++i)
    {
        for(int j=0;j<4;++j)
        {
            cout<<parr[i][j]<<" ";    //可以采用parr[i][j]
        }
        cout<<endl;
    }
    cout<<endl;
}
//注意:parr[i]等价于*(parr+i),一维数组和二维数组都适用
//第3种方式:传指针,不管是几维数组都把他看成是指针
/*void display3(int *arr)*/
void display3(int *arr,const int irows,const int icols)
{
    for(int i=0;i<irows;++i)
    {
        for(int j=0;j<icols;++j)
        {
            cout<<*(arr+i*icols+j)<<" ";   //注意:(arr+i*icols+j),不是(arr+i*irows+j)
        }
        cout<<endl;
    }
    cout<<endl;
}
int main()
{
    int arr[][4]={0,1,2,3,4,5,6,7,8,9,10,11};
    int irows=3;
    int icols=4;
    display1(arr,irows);
    display2(arr,irows);

    //注意(int*)强制转换.个人理解:相当于将a拉成了一维数组处理。
    display3((int*)arr,irows,icols);
    return 0;
}

二维数组,申请内存空间,和释放内存空间问题:

int** copyPath =new int*[rows];
for (int i = 0; i < rows; i++)
{
    copyPath[i] = new int[cols];
}



for (int i = 0; i < rows; i++)
{
    delete[] copyPath[i];
}
delete[] copyPath;


/////直接声明的方式
int arrPath[4][4] = { { 1, 3, 5, 9 }, { 8, 1, 3, 4 }, { 5, 0, 6, 1 }, { 8, 8, 4, 0 } };
12-20 11:44
查看更多