Apr 20, 2013 at 7:23am Apr 20, 2013 at 7:23am UTC
The answer is no. Not "same length". Pointers to same memory do they have.
Apr 20, 2013 at 8:07am Apr 20, 2013 at 8:07am UTC
You are trying to access already deleted items. You deleted the first three indexes and iterating them will give you unpredictable results.
Apr 20, 2013 at 8:17am Apr 20, 2013 at 8:17am UTC
I fix the code, and still, the array did not copied well:
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::nothrow;
using std::cerr;
int main()
{
int n=3;
int **m;
//The initial array:
m=new (nothrow) int *[n];
for (int i=0;i<n;i++)
{
m[i]=new (nothrow) int [3];
m[i][0]=i+1;
m[i][1]=i+2;
m[i][2]=i+3;
}
for (int i=0;i<n;i++)
cout<<m[i][0]<<" " <<m[i][1]<<" " <<m[i][2]<<" " <<endl;
cout<<"----------------------------------------------\n" ;
int **t; //The temporary array:
t=new (nothrow) int *[n*2];
for (int i=0; i<n; i++)
{
t[i]=m[i];
t[i+n]=new int [3];
cout<<t[i][0]<<" @ " <<t[i][1]<<" @ " <<t[i][2]<<endl;
}
cout<<"\n\n\n" ;
for (int i=n; i<n*2; i++)
{
for (int j=0; j<n; j++)
t[i][j]=j+i;
cout<<t[i][0]<<" % " <<t[i][1]<<" % " <<t[i][2]<<endl;
}
cout<<"\n\n\n" ;
for (int i=0;i<n;i++)
delete []m[i];
delete []m;
m=new int *[n*2];
for (int i=0; i<n*2; i++)
{
m[i]=t[i];
}
//Printing the final array:
for (int i=0;i<n*2;i++)
cout<<m[i][0]<<" " <<m[i][1]<<" " <<m[i][2]<<" " <<endl;
for (int i=0;i<n;i++)
delete []t[i];
delete []t;
return 0;
}
Here is the output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 2 3
2 3 4
3 4 5
1 @ 2 @ 3
2 @ 3 @ 4
3 @ 4 @ 5
3 % 4 % 5
4 % 5 % 6
5 % 6 % 7
0 2 3
136372240 3 4
136372256 4 5
3 4 5
4 5 6
5 6 7
Can you tell me where I wrong please?
Thank you!
Last edited on Apr 20, 2013 at 8:18am Apr 20, 2013 at 8:18am UTC
Apr 20, 2013 at 8:53am Apr 20, 2013 at 8:53am UTC
Line 17: You allocated some memory and made m[i] point to it
Line 30: You made t[i] point to same memory area as m[i]
Line 44: You deleting memory both t[i] and m[i] pointing to; both pointers now invalid.
Line 49: you are copying invalid pointer from t[i] to new m[i] array.
Last edited on Apr 20, 2013 at 8:54am Apr 20, 2013 at 8:54am UTC
Apr 20, 2013 at 9:36am Apr 20, 2013 at 9:36am UTC
Also in your code if you do
1 2 3
m[1][1] = 5;
t[1][1] = 3;
std::cout << m[1][1];
it will give you "3" because it is the same memory.
To get rid of all such behavior:
1 2 3
t[i] = new int [n];
for (size_t j(0); j < n; ++j)
t[i][j] = m[i][j];
instead of
t[i] = m[i];
Last edited on Apr 20, 2013 at 9:37am Apr 20, 2013 at 9:37am UTC