Reputation: 67
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
Upvotes: 0
Views: 75
Reputation: 310980
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.
Upvotes: 1