Problems in passing a multidimensional array to a function

Dear Sirs,
I have some problems in passing a 2D array to a function. I know that I have to define the dimensione of the second index of the array, but in my code it is defined in the main function.
This is the code for the matrix:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
double L, p_mut, mu;
  cout <<"The length of the sequence is: L= "; 
  cin >>L;
  cout<< endl;
  double totTypes = pow(2,L);
  int dimension = (int)totTypes;
(...)
 double intMatrix[dimension][dimension];//let's define the interaction matrix and initialize it to zero
   double interactStrength_temp = 0;
   for (int line=0; line<dimension; line++){
     for (int column=0; column<dimension; column++){
       infile2 >>interactStrength_temp;
       intMatrix[line][column]=interactStrength_temp;
     }
   }

This is the code for the function:

1
2
3
4
5
6
7
double hamiltonian (double array_occupancy[], int dim, int index, double matrix[][dimension], double mu, double totPop_average){
  double Hterm = 0;
  for (int i=0; i<dim; i++){
    Hterm += array_occupancy[i]*matrix[index][i];
  }
  return (1/totPop_average)*Hterm-mu*totPop_average;
}


The compiler says me that dimension is not declared in this scope and as a consequence it does not recognize the argument "matrix" as a proper matrix. Do you know how to solve this problem? I tried to define a constant but I cannot use the function pow(.,.) so I would have other problems.
Thank you very much for your help!
Yours faithfully,

Andrea Cairoli
Last edited on
1
2
3
int array1[10000], array2[10000], array3[10000];
int line = 0;
while(file >> array1[line] >> array2[line] >> array3[line]) line++;
The code is correct, but it gives me out a segmentation fault. What do you think it is the problem?
Thank you,

Andrea
please post all the errors and whatever the compiler tells you, and when possible post your code too, and please if you post your code, put them inside code syntax

Last edited on
you should verify if the end of file is reached:
1
2
while( !file.eof() )
    file>>array1[line] >> array2[line]>> array3[line++];
@chianda, can't say anything without seeing your code. Segfaults are usually caused by accessing pointers that don't point to anything. Try checking your pointers.

@Vins3Xtreme, while(file >> ...) does that. It also checks for other errors. Your code is likely to leave an empty line. It could also cause an infinite loop, if there was "hello" in the file. Moreover, the order of evaluation of function arguments is not defined, so line++ may be evaluated before other two reads from line.
Last edited on
Topic archived. No new replies allowed.