简体   繁体   中英

Modifying a 2d array passed to a function

int print(int **a, int m, int n)
{
    int i, j, sum = 0;
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            sum = sum + *((a + i*n) + j);
        }       
    }
    return sum;
}   

I got a garbage value instead of sum of the array elements. When I type-casted as

sum = sum + (int )*((a + i*n) + m));

I'm getting a correct answer. Why is that? But this method won't work for modifying the array elements. How can I do that? Please check this link for reference. http://ideone.com/VRVAxW

Try

sum = sum + *( *(a + i ) + j));

Take into account that the function can be called for an array declared like

int * a[m];

or for a pointer declared like

int **a;

Otherwise you should define the function the following way provided that your compiler supports Variable Length Arrays

int print( int m, int n, int a[][n] )
{
    int i, j, sum = 0;
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            sum = sum + *( *(a + i ) + j );
        }       
    }
    return sum;
}  

As for this expression

 (int )*((a + i*n) + m)

that is equivalent to

 (int )*( a + i*n + m )

then in any case it is wrong.

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