reallocate with new

hi all

i have a class with a table inside
the table takes memory with new
in some cases the table could take a bigger size and i want to reallocate the memory without loosing what i have inside

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
template <class T>
class Array2D
{
private : int length ;// -> max_rows
		  int multiply;
		  
public  : T **Data ;
          int size; //   -> rows
		

    Array2D() // contructors
	{
	    length   = 5;
		multiply = 2; 
			
		Data = new *T [length];
		
		size = 0;
	}
  void SetSize(int newsize)
	{
	
		if ( size > length)
		{
			for(int i=0;i<size;i++) delete [] Data[i]; 
			delete [] Data;
			for(int i=0;i<size;)
			T	** temp = new *T [multiply*newsize];
			
		    copy(Data, Data + length  , temp); 
							//length +-1

		    length = multiply*newsize;
		Data=new *T [multiply*newsize];
		   
		   
			Data = temp;
			
			
			temp = 0;
		}



i do this in setsize

but could i do that easier??or better?
You could use a C++ container class that will handle the resizing for you.
i set the setsize to this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void Setsizerow(int newsizerow)
	{
	
		if ( sizerow > lengthrow)
		{
			
			
			T	** temp = new *T [multiply*newsizerow];
			
		    copy(Data, Data + lengthrow  , temp); 
							//lengthrow +-1
			for(int i=0;i<sizerow;i++) delete [] Data[i]; 
			delete [] Data;
		    lengthrow = multiply*newsizerow;
			
			Data=new *T [multiply*newsizerow];
		   // delete [] Data;  
		   
			for(int i=0;i<sizerow;i++)
				for(int j=0;j<sizecolumn;j++) a[i][j]=temp[i][j];
		}



	}
I don't know what copy is doing (I hope it creates elements as well as copy values), but once you've filled in temp, you just need to release Data, then assign temp to Data (not copy the content all over again).
Topic archived. No new replies allowed.