How to expand an array dynamically in C++? {like in vector }

后端 未结 5 1295
有刺的猬
有刺的猬 2020-12-01 10:01

Lets say, i have

int *p;
p = new int[5];
for(int i=0;i<5;i++)
   *(p+i)=i;

Now I want to add a 6th element to the array. How do I do it

5条回答
  •  伪装坚强ぢ
    2020-12-01 10:27

    If you allocate the initial buffer using malloc you can use realloc to resize the buffer. You shouldn't use realloc to resize a new-ed buffer.

    int * array = (int*)malloc(sizeof(int) * arrayLength);
    array = (int*)realloc(array, sizeof(int) * newLength);
    

    However, this is a C-ish way to do things. You should consider using vector.

提交回复
热议问题