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?
You have to reallocate the array and copy the data:
int *p;
p = new int[5];
for(int i=0;i<5;i++)
*(p+i)=i;
// realloc
int* temp = new int[6];
std::copy(p, p + 5, temp); // Suggested by comments from Nick and Bojan
delete [] p;
p = temp;
You cannot. You must use a dynamic container, such as an STL vector, for this. Or else you can make another array that is larger, and then copy the data from your first array into it.
The reason is that an array represents a contiguous region in memory. For your example above, let us say that p points to address 0x1000, and the the five ints correspond to twenty bytes, so the array ends at the boundary of 0x1014. The compiler is free to place other variables in the memory starting at 0x1014; for example, int i
might occupy 0x1014..0x1018. If you then extended the array so that it occupied four more bytes, what would happen?
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
.
你为什么不看看来源是怎么回事vector
?您可以在 C++ 包含文件所在的文件夹中看到此机制的实现!
这是它在 gcc 4.3.2 上所做的:
使用向量的分配器分配一个新的连续内存块(您还记得向量是vector<Type, Allocator = new_allocator>
?)。默认分配器调用operator new()
(不仅仅是new
!)来分配这个块,从而让他自己不会弄乱new[]
/delete[]
东西;
将现有数组的内容复制到新分配的数组中;
使用分配器处理先前对齐的块;默认使用operator delete()
.
(请注意,如果您要编写自己的向量,您的大小应该增加“M 倍”,而不是“按固定数量”。这将让您实现摊销恒定时间。例如,如果,在每次超出大小限制,您的向量增长两次,每个元素将平均复制一次。)
Same as others are saying, but if you're resizing the array often, one strategy is to resize the array each time by doubling the size. There's an expense to constantly creating new and destroying old, so the doubling theory tries to mitigate this problem by ensuring that there's sufficient room for future elements as well.