0
votes

The following code works perfectly well if I put the function content into the main block, but the function completely fails here. I currently get a 'subscripted value is neither array nor pointer nor vector' error. I also get 'passing argument 1 and 4 of 'accumulate' from incompatible pointer type' errors.

void accumulate( double sum[], int ypos[], int xpos[], int vals[], int numvals )
{
    for(int i=0 ; i<numvals ; i++) /// start looping over indices
    {
       sum[ypos[i]][xpos[i]] += vals[i];
    }
}



int main()
{
    int xpos[2]    = {0,1};
    int ypos[2]    = {0,1};
    double vals[2] = {1.01,7};
    int numvals    = 2;
    int size       = 6;
    double sum[size][size];

    for(int i=0; i<size ;i++)
    {
        for(int j=0; j<size ; j++)
            {
            sum[i][j] = 0; // make zeros
            }
    }

    accumulate(sum,ypos,xpos,vals,numvals); // doesn't work

    for(int i=0; i<size ;i++)
    {
        for(int j=0; j<size ; j++)
            {
            printf("%f ", sum[i][j]);
            }
        printf("\n");
    }
}
1
Try these couple of fixes: 1.) put your sum variable last in the accumulate() call like this accumulate(ypos,xpos,vals,numvals, sum);. 2.) Try sending the address of the array instead of a copy of the array like this accumulate(ypos,xpos,vals,numvals, &sum); that should perform changes on the original array and not on a copy. 3.) Try writing the declaration of the accumulate function as void accumulate( ..., double sum[][]); - Ivan86
3) double sum[][] doesn't work, but double sum[][xsize] does. 2) Thanks! but this results in a warning: "passing argument 6 of 'accumulate' from incompatible pointer type. Also the note "note: expected 'double ()[(sizetype)(xsize)]' but argument is of type 'double ()[(sizetype)(ysize)][(sizetype)(xsize)]'" Not sure how to remedy. By the way, I'm new here and I can't figure out how to highlight code bits. - CJG
When you click add comment a yellow box opens with instructions on how to highlight code. As for the main problem, search google for: how to send 2D array to a function by reference in c. It's been a while since I've been programming c so I'm not fluent currently. - Ivan86

1 Answers

0
votes

2d array when passed to function that decays into T (*)[COLS]. Or alternatively you can write

void func( int col, int arr[][col]);

So you would write

void accumulate( double sum[][size], int ypos[], int xpos[], int vals[], int numvals )
{
    ...
}

Also you should be aware the ypos[i] and xpos[i] should be within the limit of the array size so that you don't run into undefined behavior.