dynamic array

i'm writing a prog in C++ and having trouble with the array of pointers. i got a fragmentation fault, so in tracked it down to a single function and added some test outputs. the code is followed by my output..

1
2
3
4
5
6
7
8
9
10
11
12
13
  int **C;
 
  cout << "m: " << m << endl;
  cout << "n: " << n << endl;
  C = new int *[m + 1];

  for(int i = 0; i < m; i++)
    C[i] = new int [n + 1];

  C[0][0] = 0;
  cout << "C[0][0] = " << C[0][0] << endl;
  C[m][n] = 0;
  cout << "C[m][n] = " << C[m][n] << endl;


output:
1
2
3
4
m: 23
n: 18
C[0][0] = 0
Segmentation fault


thanks for the help
Last edited on
1
2
  for(int i = 0; i <= m; i++)
    C[i] = new int [n + 1];


Try that? The difference is the change from < to <=

After all, if you allocated m+1 elements, why would you only use m-1? Also, that means that only elements up to, but not including, 'm' are allocated.
Are you deleting the dynamically allocated elements somewhere in the program? If not, that may be the reason you are getting segmentation fault. Cause we will get segmentation fault while there is memory leak. I think you are not deleting the dynamically allocated array. Please post your full program, then I will point out where and why you are getting error.
Rpgfan's fix is correct.
Last edited on
thanks Rpgfan, that was it.
Topic archived. No new replies allowed.