简体   繁体   中英

Array resizing using reference / pointers

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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