1

I made a small code to resize a dynamic array, passing pointer X as a reference.

void resize(int*& X , int & dimX){
int * new_X = new int [dimX+20];
 for(int i=0;i<dimX;i++)
    new_X[i] = X[i];
 delete [] X;
 X = new_X;
 dimX += 20;
}

My doubt is: what would be the difference in the code if i decided to pass the array X as a sole pointer? For example:

void resize(int* X , int & dimX)

Is that even possible for this kind of operation? (resizing). Thanks a lot and sorry for the dumb question, i'm a beginner.

3
  • Raw arrays are not "dynamic" (as you can see with the work you need to do!). Use std::vector or std::list if you need a "dynamic" collection. Commented Jul 9, 2015 at 15:28
  • @crashmstr Thanks for info :) i know about the vector class, but i just need to do a resize function by myself, and what i was wondering is: what's the best way to pass the array X to the function? and how passing int * X instead of int *&x would affect the code. Commented Jul 9, 2015 at 15:30
  • 1
    To modify a something which is passed as argument to a function you need to pass its reference or a pointer to that thing. So if you want to modify a pointer, you need to pass a reference to a pointer. Commented Jul 9, 2015 at 15:31

1 Answer 1

1

If you pass X as an int*, then you are passing a copy of the pointer. This means if you change X on the line X = new_X;, you will only update the copy, not the original.

You can either keep using a reference to the pointer like you are currently doing, or take X as an int* but return new_X and have the caller use the returned value.

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.