0

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

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. I get segmentation fault. Any idea please on how to use pointers in this case?

1
  • 6
    Declare the function as void classobj::func(double*& _vect). That said, this is horrible design and is destined to cause even more issues down the line. Commented Sep 30, 2015 at 9:02

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Well, if you use std::vector then there's no need of caring about resizing. It's performed automatically as you insert elements in the vector. Thus, you don't have to care about memory management.
are you sure it should not be (*_vect) = new double[4]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.