Extend dynamic array of pointers

Let's say we have class Example.With a constructor we initialize n pointers,but later in the program if we just want to extend that array,what is the best thing to do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include"Pointers.h"//just for example
  class Example{
private: 
int n;
Pointers **p;
public:
Example(int n)// i did not make .cpp file and there write definitions
{this->n=n;
p=new Pointers*[this->n];
for(int i=0;i<this->n;i++)
p[i]=nullptr;}
~Example(){for(int i=0;i<this->n;i++)
delete p[i];
delete [] p;
}
void Extend(int a);//Let's assume we want to extend for a places and Pointers are not nullptrs
{//is it possible to do smth like this?
n=n+a;
for(int i=n-a;i<n;i++)
p[i]=new Pointers();//calling default Pointers construction let's assume it exists
}

Is this way good?Or is there any other way?
Last edited on
Please format your code.

You only declare the initial array as having a size of n, so once you do
1
2
n = n + a;
int i = n - a;


This is like like saying
int i = (n + a) - a; or
int i = n;

which is out of bounds of your allocation.

You need to make a new array with a size of [n + a], copy the n elements from the old array into the new array, then delete[] the old array data, and re-point the pointer to point to the new array.


Alternatively, use a vector.
1
2
3
4
5
6
7
8
9
#include <vector>

int main()
{
	std::vector<int> vec(10);
	
	int a = 5;
	vec.resize(vec.size() + a);
}
Last edited on
to extend an existing pointer, you pretty much have to make a new pointer of the new size and copy all the data to it, and delete the old pointer.

your p[I] appear to all be null, so what you have is fine the first time they are allocated, but you can't 'extend' them this way.

the best way is to allocate vectors instead, to do all this for you.
next best may be using C, because alloc has a realloc capability that new lacks (but, no prize for guessing what it does for you behind the scene).


Note: Your indentation is not comfy.

Other way? Perhaps something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <vector>
#include <memory>
#include"Pointers.h"

class Example {
  std::vector<std::shared_ptr<Pointers>> p;
public:
  Example( int n )
  : p( n, std::shared_ptr<Pointers>(nullptr) )
  {}

  void Extend( const std::vector<std::shared_ptr<Pointers>>& a )
  {
    p.insert( p.end(), a.begin(), a.end() );
  }
};
Thanks for your advises.We must use dynamic memory allocation this way for our exam and also some other stuff that I do not see many people are using.We did not learn vectors or anything from STL and my term with C++ has ended now.We have only one term OOP(C++).The next term( is going to start soon) we are switching to C# and Java.
Last edited on
Topic archived. No new replies allowed.