简体   繁体   English

从外部函数/类设置动态数组的新大小?

[英]Set new size of dynamic array from an external function/class?

My main code declares a pointer that needs to be resized from an external function. 我的主代码声明了一个需要从外部函数调整大小的指针。 Ex: 例如:

double *vect =NULL;
classobj object;

object.func(vect);

//--- print the outcome
for(int j=0; j<4; ++j)
   cout << vect[j] << " .. " << endl;

where function func() is part of classobj defined in an another file (say classobj.h and .cpp ) as 其中func()函数是在另一个文件(例如classobj.h.cpp )中定义的classobj一部分, classobj

void classobj::func(double *_vect){

  _vect  = new double[4];

  for(int j=0; j<4; ++j)
    _vect[j] = 3.0*j +1 ;

};

The problem is that vect has not been resized. 问题是vect尚未调整大小。 I get segmentation fault. 我遇到细分错误。 Any idea please on how to use pointers in this case? 关于在这种情况下如何使用指针的任何想法吗?

You are passing a reference to your Array and then you are creating a new Array and assigning it to the pointer in the function. 您将传递对数组的引用,然后创建一个新的数组并将其分配给函数中的指针。 You Need to pass a pointer of the pointer and then reassign the address of that pointer: 您需要传递该指针的指针,然后重新分配该指针的地址:

void classobj::func(double **_vect){
    (*_vect)  = new double[4];

Although this solution will work I recommend using a std::vector for this purpose and passing it by reference to that function 尽管此解决方案可以工作,但我建议为此目的使用std::vector并将其通过引用传递给该函数

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

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