How to dynamically increase the array size?

前端 未结 3 1199
一向
一向 2021-02-03 12:01

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

相关标签:
3条回答
  • 2021-02-03 12:22
    #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 讨论(0)
  • 2021-02-03 12:34
       int* newArr = new int[new_size];
       std::copy(oldArr, oldArr + std::min(old_size, new_size), newArr);
       delete[] oldArr;
       oldArr = newArr;
    
    0 讨论(0)
  • 2021-02-03 12:35

    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.

    0 讨论(0)
提交回复
热议问题