当前位置:  开发笔记 > 编程语言 > 正文

C++ how to add an element to a pointer array by exceeding size

如何解决《C++howtoaddanelementtoapointerarraybyexceedingsize》经验,为你挑选了1个好方法。

assume that we created dynamically allocated memory such as:

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

it will assing 0 to 9 to our pointer array.
Then i wanted to add 10,11,12 to the array
can i do :

p[10] = 10;
p[11] = 11;
p[12] = 12;

or should i do:

delete[] p;
size = 13;
p = new int[SIZE];
for(int i = 0; i < SIZE; ++i)
  p[i] = i;

Vlad from Mo.. 7

You have to reallocate memory for the array of a greater size. Otherwise the program will have undefined behavior.

For example

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

int *tmp = new int[SIZE + 3];

std::copy( p, p + SIZE, tmp );
delete []p;
p = tmp;

p[SIZE++] = 10;
p[SIZE++] = 11;
p[SIZE++] = 12;

Or instead of the last three statements you can write

for ( const int &value : { 10, 11, 12 } ) p[SIZE++] = value;

Of course in such cases it is better to use the standard container std::vector.

In fact the code above is similar to the following

#include 

//...

std::vector v( 10 );

for ( int i = 0; i < v.size(); i++ ) v[i] = i;

v.reserve( 13 );
for ( const int &value : { 10, 11, 12 } ) v.push_back( value );

except that all the memory management is done internally by the vector.



1> Vlad from Mo..:

You have to reallocate memory for the array of a greater size. Otherwise the program will have undefined behavior.

For example

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

int *tmp = new int[SIZE + 3];

std::copy( p, p + SIZE, tmp );
delete []p;
p = tmp;

p[SIZE++] = 10;
p[SIZE++] = 11;
p[SIZE++] = 12;

Or instead of the last three statements you can write

for ( const int &value : { 10, 11, 12 } ) p[SIZE++] = value;

Of course in such cases it is better to use the standard container std::vector.

In fact the code above is similar to the following

#include 

//...

std::vector v( 10 );

for ( int i = 0; i < v.size(); i++ ) v[i] = i;

v.reserve( 13 );
for ( const int &value : { 10, 11, 12 } ) v.push_back( value );

except that all the memory management is done internally by the vector.

推荐阅读
N个小灰流_701
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有