This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: variable length arrays as arguments to functions


Hi Maarten,

In C++ if a function is called with an array as an argument, the address of the first element of the array is passed to the function. C++ computes the actual address of each element from this base address plus the number of elements in each column. For this reason the number of columns in a 2 dimensional array (or values for all but first dimension of an n dimensional array) is needed.
If you define
void MyFunc(int N, float my_matrix[][5]);		// you may skip defining the rows for now
and use it as
void MyFunc(int N, float my_matrix[][5])
{    	.  
	.
	.
}

This should work. In a large programe you might want to use macros defined at the start used as dimensions in the array.
The new version of C language C9X also supports this but might have protability issues.

best regards,
Pradyuman.

-----Original Message-----
From: Maarten Speekenbrink [mailto:M.Speekenbrink@uva.nl]
Sent: Tuesday, June 03, 2003 1:59 PM
To: gcc-help@gnu.org
Subject: variable length arrays as arguments to functions


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])

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}
    };

    MyFunc(5, Q);

    return 0;

}

void MyFunc(int N, float my_matrix[N][N])
{

    for (int i=0; i<N; i++){
        float sum = 0;
	  for (int j=0; j<N; j++) {
            sum = sum + Q[i][j];
        }
        cout << "Rowsum is: " << sum << '\n';
    }
}


       
---------------------------------------------------------------------
  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
---------------------------------------------------------------------


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]