C++ 如何动态增加数组大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12032222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically increase the array size?
提问by EEstud
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
我一直在尝试制作一个添加 2 个不同大小数组的程序。但是我想知道动态增加数组大小的容量?例如:array[4] 然后将大小升级到 2 以制作 array[6];? 编辑:不使用向量
I tried creating a new ptr but it does not work. I get the error: Read only variable is not assignable.
我尝试创建一个新的 ptr,但它不起作用。我收到错误:只读变量不可分配。
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;
回答by David Schwartz
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.
你不能改变数组的大小,但你不需要。您可以只分配一个更大的新数组,复制要保留的值,删除原始数组,并将成员变量更改为指向新数组。
Allocate a new[] array and store it in a temporary pointer.
Copy over the previous values that you want to keep.
Delete[] the old array.
Change the member variables,
ptr
andsize
to point to the new array and hold the new size.
分配一个 new[] 数组并将其存储在一个临时指针中。
复制要保留的先前值。
删除 [] 旧数组。
更改成员变量,
ptr
并size
指向新数组并保持新大小。
回答by Sanjay Agarwal
int* newArr = new int[new_size];
std::copy(oldArr, oldArr + std::min(old_size, new_size), newArr);
delete[] oldArr;
oldArr = newArr;
回答by tech dreams
#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;
}