Getting segfault with pointer to pointer

Hi everybody. I'm trying to store an array of vectors using a double pointer as a 2D array, but after the first "vector" (column) has been filled, I get a segfault.
I correctly included all the libraries needed, and declared all the variables; I am using this function to allocate the space for the array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double **vec_array(int rows,int clms) 
/*allocates a double matrix with -rows- rows and -clms- columns */
{
  int i;
  double **m;

  m = (double **)calloc(rows+1, sizeof(double *));

  m[0] = (double *)calloc(clms+1, (rows+1)*sizeof(double));
  for ( i = 1 ; i <= rows ; i++ ) 
  { 
    m[i] = m[0]+i*(clms+1); 
  }

  return m;
}


and this is my main:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main(int argc, char** argv)
{
 int i, N; //N is the number of points to which the vectors point
 FILE *input;
 double **vecs; //array of vectors
 vecs=vec_array(N,3);
 input=fopen(argv[1], "r");
 fscanf(input, "%d\n", &N);
 for(i=0; i<N; i++)
 {
  fscanf(input, "%lf %lf %lf\n", &vecs[i][0], &vecs[i][1], &vecs[i][2]);
  /*CHECK!*/ //fprintf(stderr, "%lf %lf %lf\n%, vecs[i][0], vecs[i][1], vecs[i][2]); 
/*as a check of the correct assingment of the components of the i-th vector*/ 
 } 

 ... //stuff my program needs to do with acquired data
 
 return 0;
}


argv[1] contains the name of the input file, which is formatted the following way:

1
2
3
4
5
N
1st_point_x 1st_point_y 1st_point_z
2nd_point_x 2nd_point_y 2nd_point_z
    :           :            :
N-th_point_x N-th_point_y N-th_point_z 
.

I get no error while compiling, but when I run the program I get a segfault right after having read the first vector: switching on the check I get in my output just the components of the first vector and then the segfault:

1
2
3
4
5
Terminal:

$ ./myprog input_data.dat
0.000000 0.512468 -0.152468
Segmentation fault (core dumped)


Has anyone a clue of what is going on?
Last edited on
You have not initialized N.
Oh, thanks. This is embarassing.
Topic archived. No new replies allowed.