0

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.

3
  • 1
    You cannot use variable values in a declaration. Commented Sep 5, 2015 at 10:44
  • Heard about pointers? Commented Sep 5, 2015 at 10:54
  • Pass a pointer and length of the array to your function. The pointer will point at the beginning of some array and the length will tell you how many cells it has (if you want to iterate or something). Commented Sep 5, 2015 at 11:00

1 Answer 1

2

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 .

Sign up to request clarification or add additional context in comments.

1 Comment

You don't need to specify the template parameters. You can say sumcol(temp);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.