Problem with a program

Hi everybody! I need somebody's help. I have a segmentation fault in this program and don't know how to fix it. 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
51
52
53
54
#include <iostream>

#define C 3
#define R 4

using namespace std;

void d(int**);

void f(int mat[][4])
{
	int **p, **n;
	int *h;
	
	p=new int*[C];
	for(int i=0; i<C; i++)
		p[i]=new int[R];
	
	n=new int*[C];
	for(int i=0; i<C; i++)
		n[i]=new int[R];

	for(int i=0; i<C; i++)
	{
		for(int j=0; j<R; j++)
			p[i][j]=mat[i][j];
	}

	n=p;
        int i, j;
	for(n=p, i=0; i<C; n++, i++)
	{
		for(h=*n, j=0; j<R; h++, j++)
			cout<<*h<<" ";
		cout<<endl;
	}
	d(p);   //I have a segmentation fault in line
	d(n);   //or in this one, I exactly don't know
}

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

int main()
{
	int mat[C][R]={{1,2,3,4},{1,2,3,4},{1,2,3,4}};
	f(mat);

	return 0;
}
Last edited on
This program won't compile for me. It has several errors in the following snippet:
1
2
3
4
5
6
7
	n=p;
	for(n=p, i=0; i<C; n++, i++)
	{
		for(h=*n, j=0; j<R; h++, j++)
			cout<<*h<<" ";
		cout<<endl;
	}

Several of the variables are giving errors because they have not been defined.

Oh, I'm sorry during coppying this program here I missied 1 string. Fixed now.
Last edited on
After n=p; has been executed, the original value of n is lost.
Call function d before that line:
1
2
	d(n);  
	n=p;
First why are you trying to delete the same memory twice? When you assigned n to p on line 29 you lost the pointer to the memory n was pointing to. The same in your loop assignment. So when you try to delete n in your function n no longer points to valid memory, you already deleted p.

Chervil, thanks. You helped me very much.
Topic archived. No new replies allowed.