How to dynamically increase the size of an array?

I tried to create a program that adds 2 arrays of different sizes. But I would like to know to dynamically increase the capacity of an array? Example: array [4], then update the size to 2 to create an array [6] ;? EDIT: using vectors

I tried to create a new ptr, but it does not work. I get an error: a read-only variable is not assigned.

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;
+6
source share
5 answers

You cannot resize the array, but you do not need it. You can simply select a new array that is larger, copy the values ​​you want to keep, delete the original array and change the member variable to point to the new array.

  • Select the new array [] and save it in a temporary pointer.

  • , .

  • [] .

  • -, ptr size, .

+14
   int* newArr = new int[new_size];
   std::copy(oldArr, oldArr + std::min(old_size, new_size), newArr);
   delete[] oldArr;
   oldArr = newArr;
+3

++ ( ).

Facebook : Facebook Vector

0

.

0
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p,*q;
int i;
p=(int *)malloc(5*sizeof(int));
p[0]=3;p[1]=5;p[2]=7;p[3]=9;p[4]=11;
q=(int *)malloc(10*sizeof(int));
for(i=0;i<5;i++)
q[i]=p[i];
free(p);
p=q;
q=NULL;
for(i=0;i<5;i++)
printf("%d \n",p[i]);
return 0;
}
0

All Articles