Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c++ - How to dynamically increase the array size?

I've been trying to make a program that adds 2 arrays of different size. But I would like to know to to dynamically increase the array size capacity? Ex: array[4] then upgrade the size to 2 to make array[6];? EDIT: WIthout using vectors

I tried creating a new ptr but it does not work. I get the error: Read only variable is not assignable.

int *ptr2 = new int[a2.size];


            // new ptr2 copies ptr1
            for (int i=0; i<(a1.size); i++) {
                ptr2[i] = a1.ptr[i];
            }


            // we want ptr1 to point to ptr2
            for (int i=0; i<(a2.size); i++) {
                ptr2[i] += a2.ptr[i];
            }

            delete [] a1.ptr;

            a1.ptr=ptr2;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array.

  1. Allocate a new[] array and store it in a temporary pointer.

  2. Copy over the previous values that you want to keep.

  3. Delete[] the old array.

  4. Change the member variables, ptr and size to point to the new array and hold the new size.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...