delete 2d array

Hi everybody! I spent 3 hours at this code and haven't figured out how to delete 2d array from dynamical memory. I think something wrong with my function free(), but I'm not sure. Please help.
Here is a 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>

#define COL 3
#define ROW 5

using namespace std;

int** Array(int arr[][ROW])
{
	int **pd;
	pd=new int*[COL];
	for(int i=0; i<ROW; i++)
		pd[i]=new int[ROW];

	for(int i=0; i<COL; i++)
	{
		for(int j=0; j<ROW; j++)
		{
			pd[i][j]=arr[i][j]; 
		}
	}
	//some code	
	return pd;
}

void free(int **p)
{
	for(int i=0; i<ROW; i++)    
		delete [] p[i];     
	delete [] p;                
}

int main()
{
	int arr[COL][ROW]={{1,89,12,2,44},{23,5,32,16,18},{22,5,7,45,67}};
	int **p;
	
	p=Array(arr);
	for(int i=0; i<COL; i++)
	{
		for(int j=0; j<ROW; j++)
		{
			cout<<p[i][j]<<" ";
		}
		cout<<endl;
	}
	free(p);  
	
	return 0;
}
Line 11: You've allocated an array of size 3.

Lines 12, 13: You're assigning values to an array of expected size 5. So pd[3] and pd[4] refer unallocated memory. This would at least fail at line 29.
The first index denotes rows while the second index denotes columns. So instead of

1
2
3
	pd=new int*[COL];
	for(int i=0; i<ROW; i++)
		pd[i]=new int[ROW];


it would be correctly to write

1
2
3
	pd=new int*[ROW];
	for(int i=0; i<ROW; i++)
		pd[i]=new int[COL];


To delete an array allocated dynamically you shall use operator delete []pointer;
Last edited on
As I understood you I should change at line 28 for(int i=0; i<ROW; i++) to for(int i=0; i<COL; i++). I have done, but it didn't help.
PLEASE: Be more precisely. What happens? What kind of error message will be reported? ...
well, it's indeed so (to match the loops):
1
2
3
	pd=new int*[COL];
	for(int i=0; i<COL; i++)
		pd[i]=new int[ROW];


line 28:
for(int i=0; i<COL; i++)



2d arrays are hard to understand...
The first index denotes rows while the second index denotes columns. So instead of


1
2
3
	pd=new int*[COL];
	for(int i=0; i<ROW; i++)
	     pd[i]=new int[ROW];


it would be correctly to write

1
2
3
	pd=new int*[ROW];
	for(int i=0; i<ROW; i++)
	      pd[i]=new int[COL];



Are you sure? Because after your interpretation I have mistakes in a string of integer.
May be that's your problem: You're assigning a 3x5 matrix to an 5x3.
coder777, your advise is right, thanks!
Thanks all for a help! It is fixed.
When you create a line of memory, you have to loop through the line of the proper size.

on line 11 you create an array of size 5, but loop only three times. You'll want to loop the amount that is equal to the size of the created memory.
Topic archived. No new replies allowed.