将二维数组传递给 C++ 函数 [英] Passing a 2D array to a C++ function

查看:35
本文介绍了将二维数组传递给 C++ 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我想将一个可变大小的二维数组作为参数.

I have a function which I want to take, as a parameter, a 2D array of variable size.

到目前为止我有这个:

void myFunction(double** myArray){
     myArray[x][y] = 5;
     etc...
}

而且我在代码的其他地方声明了一个数组:

And I have declared an array elsewhere in my code:

double anArray[10][10];

但是,调用 myFunction(anArray) 会给我一个错误.

However, calling myFunction(anArray) gives me an error.

我不想在传入数组时复制它.在 myFunction 中所做的任何更改都应该改变 anArray 的状态.如果我理解正确,我只想将指向二维数组的指针作为参数传入.该函数还需要接受不同大小的数组.例如,[10][10][5][5].我该怎么做?

I do not want to copy the array when I pass it in. Any changes made in myFunction should alter the state of anArray. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example, [10][10] and [5][5]. How can I do this?

推荐答案

向函数传递二维数组的三种方式:

There are three ways to pass a 2D array to a function:

  1. 参数是一个二维数组

  1. The parameter is a 2D array

int array[10][10];
void passFunc(int a[][10])
{
    // ...
}
passFunc(array);

  • 参数是一个包含指针的数组

  • The parameter is an array containing pointers

    int *array[10];
    for(int i = 0; i < 10; i++)
        array[i] = new int[10];
    void passFunc(int *a[10]) //Array containing pointers
    {
        // ...
    }
    passFunc(array);
    

  • 参数是一个指针的指针

  • The parameter is a pointer to a pointer

    int **array;
    array = new int *[10];
    for(int i = 0; i <10; i++)
        array[i] = new int[10];
    void passFunc(int **a)
    {
        // ...
    }
    passFunc(array);
    

  • 这篇关于将二维数组传递给 C++ 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆