variable length arrays as arguments to functions
Alcino Dall Igna Junior
alcino@lncc.br
Fri Jun 6 14:39:00 GMT 2003
As I see, in fact, matrices doesn't exist, so, the easiest way seems to
me to be:
On Tue, 2003-06-03 at 05:28, Maarten Speekenbrink wrote:
> I am trying to write a function in c++ that takes a square matrix of variable dimension as its argument. I read in the manual that this should be possible in g++. However, I am experiencing some trouble. I am a novice in c++, so it could be in my code or in the compiler. For instance, when I try the code below, I get an error for the function declaration that N is not specified. Is there a way to write functions for variable-size two dimensional arrays? (I am using the Mingw port of g++).
> Thanks for your help,
> Maarten
>
> // Program
>
> #include <iostream>
> using namespace std;
>
> void MyFunc(int N, float my_matrix[N][N])
void MyFunc(int N, float my_matrix[])
>
> int main()
> {
> float Q[5][5] = {
> {0.90, 0.85, 0.70, 0.85, 0.70},
> {0.85, 0.90, 0.70, 0.85, 0.70},
> {0.60, 0.60, 0.90, 0.60, 0.60},
> {0.60, 0.60, 0.60, 0.90, 0.60},
> {0.50, 0.50, 0.50, 0.50, 0.50}
> };
float Q[5*5] = {
0.90, 0.85, 0.70, 0.85, 0.70,
0.85, 0.90, 0.70, 0.85, 0.70,
0.60, 0.60, 0.90, 0.60, 0.60,
0.60, 0.60, 0.60, 0.90, 0.60,
0.50, 0.50, 0.50, 0.50, 0.50
};
>
> MyFunc(5, Q);
>
> return 0;
>
> }
>
> void MyFunc(int N, float my_matrix[N][N])
void MyFunc(int N, float my_matrix[])
> {
int size = N * N;
>
> for (int i=0; i<N; i++){
for (int i=0; i< size; i+=N){
> float sum = 0;
> for (int j=0; j<N; j++) {
> sum = sum + Q[i][j];
sum = sum + Q[i+j];
> }
> cout << "Rowsum is: " << sum << '\n';
> }
> }
>
>
In this way the changes are minimal, as clear as, and more efficient,
or in a even more efficient way, it could be done using pointers
directly.
The use of many indexes appear to be clearer, but adds a lot of
overhead, what is not the C/C++ way.
>
> ---------------------------------------------------------------------
> Maarten Speekenbrink
> Psychological Methodology
> Department of Psychology, Faculty of Social and Behavioral Sciences
> address: Roetersstraat 15, 1018 WB Amsterdam, Netherlands
> tel: +31 20 525 6876 / +31 20 525 6870
> fax: +31 20 639 0026
> ---------------------------------------------------------------------
>
>
More information about the Gcc-help
mailing list