[英]multidimensional array initialization using pointers
I want to have a function which initializes dynamic 2d arrays in cpp like below 我想有一个可以在cpp中初始化动态2d数组的函数,如下所示
void initArrays(int n,double **a,double **b,double **c) {
a = new double*[n];
for (int i = 0; i < n; i++)
a[i] = new double[n];
b = new double*[n];
for (int i = 0; i < n; i++)
b[i] = new double[n];
c = new double*[n];
for (int i = 0; i < n; i++)
c[i] = new double[n];
}
The function call completes but it does not initialize the pointers I give as function arguments. 函数调用已完成,但没有初始化我作为函数参数给出的指针。 For example if I call this function in the main 例如,如果我在主菜单中调用此函数
double **x,**y,**z;
initArrays(3,x,y,z);
I cannot access 我无法访问
x[0][0]
what am I doing wrong here? 我在这里做错了什么?
The pointers stay uninitialized because you never assign them a value. 指针保持未初始化状态,因为您从未为它们分配值。 The pointers in your init function are copies of the ones that you passed. init函数中的指针是您传递的指针的副本。 You can pass the pointers by reference: 您可以通过引用传递指针:
void initArrays(int n,double **&a,double **&b,double **&c)
That said, you'll probably be better off with std::vector
. 也就是说,使用std::vector
可能会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.