2 dimensional array
Jul 13, 2010 at 10:11pm UTC
I have the following sample code:
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
#include<iostream>
using namespace std;
int main(){
int **m;
m= new int *[10];
for (int i=0;i<10;i++)
{
m[i]=new int [5];
}
for (int i=0;i<10;i++)
for (int j=0;j<5;j++)
m[i][j]=4;
cout<<m[0][3]<<endl;
for (int i=0;i<10;i++)
{
delete []m[i];
}
delete []m;
return 0;
}
This works fine. But if I change the line
m= new int*[10];
to
m= new int*;
I get the output, but the deletion part is not working fine and the program is not terminated.
I cannot understand how I am able to access the value in the second case when I put the initialization as m= new int*;
Can someone please explain this?
Thanks.
Jul 13, 2010 at 10:48pm UTC
m= new int *[10]
create 10 new pointers.
m= new int *
creates just ONE new pointer.
So if you just took all the above code and change that one line:
1. All the loops will be wrong (and could cause crashes)
2. Delete [] is wrong when you haven't created a new array.
** You get the output when you change to new int* - but you are causing heap corruption/access violation**
Jul 14, 2010 at 2:03am UTC
This would be a good use for some defines.
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
#include<iostream>
using namespace std;
#define NUM_INT_PTRS 10
#define NUM_INTS 5
int main(){
int **m;
m= new int *[NUM_INT_PTRS ];
for (int i=0;i<NUM_INT_PTRS ;i++)
{
m[i]=new int [NUM_INTS];
}
for (int i=0;i<NUM_INT_PTRS ;i++)
for (int j=0;j<NUM_INTS;j++)
m[i][j]=4;
cout<<m[0][3]<<endl;
for (int i=0;i<NUM_INT_PTRS ;i++)
{
delete []m[i];
}
delete []m;
return 0;
}
Jul 14, 2010 at 3:01am UTC
There's no need for such macro hackery in C++:
1 2
const size_t PtrArraySize = 10;
const size_t IntArraySize = 5;
Last edited on Jul 14, 2010 at 3:06am UTC
Topic archived. No new replies allowed.