简体   繁体   English

二维数组的指针可用于C ++

[英]Pointer of Two dimensional array to function c++

Im kind of begginer in C++, just to programming in PHP and JAVA, I have problem to make a pointer to 2d array, then use this pointer in different function and cout values of [0] and [1]. 我是C ++的初学者,仅是PHP和JAVA编程人员,我有一个问题要创建一个指向2d数组的指针,然后在[0]和[1]的不同函数和cout值中使用此指针。

There is part of my script. 我的脚本有一部分。

    int size_dd = 5;
    int dd[size_dd][2];

    for (int i = 0; i < size_dd; i ++)
    {
        dd[i][0] = 2 * i + 10;
        dd[i][1] = 4 * i + 20;
    }

I can read the dd[i][0] in main function but I cannot call them in function read(int* twodarray), as it returns int[int] and the 2nd parameter from array is lost. 我可以在主函数中读取dd [i] [0],但不能在函数read(int * twodarray)中调用它们,因为它返回int [int]且数组中的第二个参数丢失。

Thing is that I need to make pointer to this array and call it in other function. 问题是我需要指向该数组并在其他函数中调用它。

But the problem is when I handle *dd in to the function, it return that dd is int[int] value instead of int[int][int], how can I resolve it? 但是问题是当我在函数中处理* dd时,它返回dd是int [int]值而不是int [int] [int],我该如何解决呢?

Your function should have following signature: 您的函数应具有以下签名:

void fooByPtr(int(*arr)[5][6]) {
  (*arr)[4][4] = 156;
}

// Call ex:
int dd[5][6];
fooByPtr(&dd);

You can also do it with reference and template: 您也可以使用参考和模板来做到这一点:

void fooByRef(int (&arr)[5][6]) {
  arr[4][4] = 156;
}

template<int N, int M>
void fooByRefTempl(int(&arr)[N][M]) {
  arr[4][4] = 156;
}

Some other comments to your code (also the one from comment): 您的代码的其他一些注释(也是注释中的注释):

You can create arrays using constant values as sizes, so this is wrong: 您可以使用常量值作为大小来创建数组,所以这是错误的:

    int size_dd = 5;

and should be: 并且应该是:

    const int size_dd = 5;

in your fun_call you should dereference your array: (*dwu_wymiar) before indexing it. 在您的fun_call中,应在对数组进行索引之前取消引用它的数组(*dwu_wymiar)

finally, change funCall(int(*dwu_wymiar)[][2], to int(*dwu_wymiar)[5][2] , as in my example above. 最后, funCall(int(*dwu_wymiar)[][2], ,将funCall(int(*dwu_wymiar)[][2],更改为int(*dwu_wymiar)[5][2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM