0

I have a function which takes as input, a pointer to a 2D array, and a pointer to a 1D array.

int resize(double *x, double **y, int n){

The aim of this function is to resize both x and y to be twice their length (n).

I create two new arrays- which have been doubled in length

double **yTemp = NULL;
double *xTemp = NULL;
xTemp = new double[2*n + 1];
yTemp = new double*[2*n + 1];

I then loop through and replace the values of xTemp with and yTemp with x and y

After then setting them equal to one other:

        y = yTemp;
        x = xTemp;
        return 2*n;

and exiting the function, y and x seem to lose the extra length.

Any help on this would be great!

8
  • 2
    You pass the pointers by value. If you want to change them in the function and have the caller get the new value, you have to pass them by reference. Also, make sure to free[] the old values. (But why not use vectors and avoid all this complex, fragile nonsense?) Commented Sep 30, 2015 at 5:17
  • Sorry, i'm a bit new to this, would it just be free(xTemp); free(yTemp); ? Commented Sep 30, 2015 at 5:20
  • probably this answer will help you Commented Sep 30, 2015 at 5:23
  • 1
    @aeongrail That's correct for when you're done with them. If you expect yTemp, however, you probably don't want to delete the inner elements because they'll be part of the expanded array (perhaps, it depends on your exact implementation). But please, just use something like std::vector. Commented Sep 30, 2015 at 5:35
  • 1
    @aeongrail You do not delete variables in C++ (or any language I'm aware of); you delete objects. You want the function to delete the old, smaller arrays that you're no longer going to be using. Commented Sep 30, 2015 at 5:49

1 Answer 1

5

Your assignments to y and x before the return are setting the local values of those variables, not the ones passed in from the caller. To do that, you can change your function declaration to

int resize(double *&x, double **&y, int n){

which will allow changing the caller's values.

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

Comments

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.