简体   繁体   中英

Passing a 2d-Array with an unknown row and column size to a function (C++)

I got this function so far :

void sumcol(int a[r][c],int r,int c){
int i,j,sum=0;
//int sizec= sizeof(a)/sizeof(a[0][0]);
//int sizer= sizeof(a)/sizeof(a[0]);

for (i=0;i<r;i++){
    for (j=0;j<c;j++) sum=sum+a[j][i];
    cout<<"Suma pe coloana "<<i<<" este : "<<sum<<endl;
    sum=0;
}
}

I get an error on the first line that r and c were not declared in this scope. Why? Though I read right there : https://www.eskimo.com/~scs/cclass/int/sx9a.html that this is a Correct way of declaring.

I think your real problem is passing 2d array into function. If you know your array size in compile time I will advice something like:

template <int r, int c>
void sumcol(int (&a)[r][c]){
    int i,j,sum=0;
    //int sizec= sizeof(a)/sizeof(a[0][0]);
    //int sizer= sizeof(a)/sizeof(a[0]);

    for (i=0;i<r;i++){
        for (j=0;j<c;j++) sum=sum+a[j][i];
        std::cout<<"Suma pe coloana "<<i<<" este : "<<sum<< std::endl;
        sum=0;
    }
}

and calling it like forexample :

int main()
{

    int temp[3][5]; // You don't forget to initialize this in your real code
    sumcol(temp); 
}

Or if you are using dynamiccally allocated matrix array(malloc). Than use something like:

void sumcol(int** a,int r,int c){
      do stuff

Consider reading this thread first Passing a 2D array to a C++ function

I personally find it easier to do this stuff with cool C++ Vectors instead C arrays .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM