How to dynamically increase the array size?

Viewed 113783

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;
5 Answers
#include<bits/stdc++.h>
using namespace std;

main(){
    
    int *p = new int[5]; // locate memory in heap
    int *q = new int[10];// locate memory in heap
    
    for(int j=0; j<5;j++)
        p[j] = j;
    
    for(int i=0; i<5;i++)
        q[i] = p[i];
        
    delete []p;//Delete the old array 'p'
    p = q; // Assign the pointer of 'q' to 'p'
    q = NULL; // delete the location of pointer 'q'
    
    return 0;
}

It may be late too answer but i'll explain some things to you..

Array Size cannot be increase because of contiguous memory allocation in the memory. For Example => The address of the every location is

arr[5] => [2001,2002,2003,2004,2005]

Now, The main problem is if you allocate it to arr[10] so, as we don't know the next location 2006 will be free . because array need to be in contiguous so, we won't be able to allocate memory

From my Suggestions use Vector or use dynamic Memory allocation in Cpp

int *old = new int[5];
int *nw = new int[10];

for (size_t i = 0; i < sizeof(old); i++)
    nw[i] = old[i];

delete []old;
old = nw;
nw = NULL;
#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;
}
Related