指向指针(2D数组)的指针作为输入参数

[英]Pointer to a pointer (2D array) as input parameter


I started studying C++ at university 2 months ago, and I'm trying to figure out how to pass a dynamic 2d array (pointer to pointer) to a function as an input parameter. I have this dynamic 2d array:

我在2个月前开始在大学学习C ++,我试图找出如何将动态2d数组(指针指针)作为输入参数传递给函数。我有这个动态的2d数组:

int **p;
p = new int*[R];
for(i=0; i<R; i++)
    p[i] = new int[C];

Now I want to pass this pointer p to a function as an input parameter, using const. I mean that I want the function not to be able to modify the elements of the matrix.

现在我想使用const将此指针p作为输入参数传递给函数。我的意思是我希望函数不能修改矩阵的元素。

I tried like that:

我试过这样的:

void func(const int **p) {
}

But i get this error:

但我得到这个错误:

main.cpp:19:11: error: invalid conversion from 'int**' to 'const int**' [-fpermissive]

main.cpp:19:11:错误:从'int **'到'const int **'的无效转换[-fpermissive]

main.cpp:9:6: error: initializing argument 1 of 'void func(const int**)' [-fpermissive]

main.cpp:9:6:错误:初始化'void func(const int **)'的参数1 [-fpermissive]

I tryied using typedef and it works, but it's not constant. If i do like that:

我尝试使用typedef并且它可以工作,但它不是恒定的。如果我喜欢这样:

typedef int** abc;

void func(const abc p);

main() {
abc p;
...
func(p);
}

The source compiles but function 'func' is able to modify values of "p matrix"; I want p to be an input parameter, it has to be read-only!

源编译但函数'func'能够修改“p matrix”的值;我希望p是一个输入参数,它必须是只读的!

Please, how can I pass a pointer-to-pointer to a function flagging the elements as read-only?

请问,如何将指向指针的指针传递给将元素标记为只读的函数?

Thank you in advance for you help and sorry for my bad english.

提前谢谢你的帮助,抱歉我的英语不好。

3 个解决方案

#1


3  

Your const int **p should be a const int * const *p. The conversion from const int ** to int ** isn't allowed to be implicit, because it could violate the constness of the values being pointed to. To see why, look at the following code extract taken from the C standard (§6.5.16.1):

你的const int ** p应该是一个const int * const * p。从const int **到int **的转换不允许是隐式的,因为它可能违反指向的值的常量。要了解原因,请查看以下从C标准(第6.5.16.1节)中获取的代码摘录:

const char **cpp;
char *p;
const char c = 'A';

cpp = &p;       // constraint violation
*cpp = &c;      // valid
*p = 0;         // valid

If cpp = &p was a valid assignment, the subsequent code would be able to set the value of c to 0, despite the value being a const char.

如果cpp =&p是有效赋值,则后续代码将能够将c的值设置为0,尽管该值是const char。

#2


2  

void func(const int * const *p) {
}

#3


1  

Try this:

typedef const int *cint_ptr_t  ;

void func(const cint_ptr_t  *p) {
}

Keep in mind that you want to be const the elements of your 2D array and the pointers to the beginning of each row

请记住,您希望成为二维数组的元素和指向每行开头的指针

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/12/13/2c5a2bbe9797dac9297ef7f726c8128e.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告