Dynamic Matrix

Hi,i want to delete from dynamic matrix the first row, where the sum of the elements is more than 10. Here is my code. Why doesn't it work properly?
When it finds the row where s>10 it stops and doesn't print out the following rows.

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
  #include<iostream>
using namespace std;
void main()
{
	double **p,s;
	int i,j,n,k;
	cin>>n>>k;
	p=new double*[n]; if(p==NULL) return;

	for(i=0;i<n;i++)
	{
		for(j=0;j<k;j++) 
			p[i]=new double[k];
		if(p[i]==NULL) return;
	}

	for(i=0;i<n;i++) for(j=0;j<k;j++) cin>>p[i][j];

	for(i=0;i<n;i++) 
	{
		s=0; 
		for(j=0;j<k;j++) s+=p[i][j];
		if(s>10) { delete[] p[i]; p[i]=NULL; break; }
	}
	cout<<endl;
	for(i=0;i<n;i++)
	{
		for(j=0;j<k;j++) cout<<p[i][j]<<" ";
		cout<<endl;
	}

	for(i=0;j<n;i++) delete[] p[i]; delete[] p;

}
closed account (D80DSL3A)
On line 28 you read from memory without 1st checking if that memory still exists.
Some rowsOne row may have been deleted (just noticed the break; on line 23).

Insert a line before line 28 to check if p[i]==NULL, then take appropriate action (continue;?).

Massive memory leak alert! At line 13 you assign an array of doubles to p[i] a total of k times. The 1st k-1 allocations are just thrown away! Only the last one sticks.
Move lines 13 and 14 above line 12. Incidentally, the version of new you're calling won't return NULL on allocation failure. It will throw an exception. Use the "no throw" version of new instead.

Line 32. You may be calling delete[] on an already deleted row. Since you've assigned p[i]=NULL this should be harmless (so I've heard), but still... discipline!!
Personally, I would check for p[i]==NULL before calling delete[] p[i];

Finally, void main()? Someone is still teaching this?
The standard has been int main() for many years.
Last edited on
thank you
Topic archived. No new replies allowed.