Adding row to dynamic matrix

Hi, I wanna add a row that follows the first row where all the elements are prime numbers. Please help, why doesn't my code work. I guess the loop where i try to lower the following rows to add my new row doesn't work properly.

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
  #include<iostream>
using namespace std;
bool prime(int[],int);
int main()
{
	int **p,i,j,n,m,k,q;
	cin>>n>>k;
	p=new int*[n]; if(p==NULL) { cout<<"I have no memory."; return 0; }
	for(i=0;i<n;i++)
	{
		p[i]=new int[k]; if(p[i]==NULL) { cout<<"I have no memory."; return 0; }
	}

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

	for(i=0;i<n-1;i++) 
		if(prime(p[i],k)) 
		{
			for(q=n-1;q>i+1 ;q--) p[q]=p[q-1];
			cout<<"Input your new row"<<endl;
			for(m=0;m<k;m++) cin>>p[i+1][m];
			break;
		}
		
		cout<<endl;
		for(i=0;i<n;i++) 
			{
				for(j=0;j<k;j++) cout<<p[i][j]<<" ";
				cout<<endl;
			}
		for(i=0;i<n;i++)delete[] p[i]; delete[] p;
return 0;
}
bool prime(int a[],int l)
{
	int q=0;
	for(int i=0;i<l;i++) 
	{
		for(int x=1;x<a[i]/2;x++) 	if(a[i]%x==0) return false;
		q++;
	}		
	return q==l;
}
Let n=4.

You allocate:
p[0] = A
p[1] = B
p[2] = C
p[3] = D

You fill A, B and C. Let say that the A "is prime".

You rearrange pointers:
p[3] = C
p[2] = B

Now you fill p[1], which still points to B, just like the p[2]. Is that the error you see (inserted and following rows being same)?

The icing on the cake: Nobody remembers the D -- a leak -- and there will be two attempts to delete the B.
i have to set p[1] to NULL, than cin>>p[1]?
closed account (D80DSL3A)
I think his point is that you're overwriting the address held by the last pointer p[n-1]. You must save that value before shifting all down so you can copy it to p[i+1] after the shift.
Topic archived. No new replies allowed.