Hans
Hans

Reputation: 451

C Programming - Sum of 2D arrays

I am trying to get the values of diagonal values from a 2D array. For example..

10 20 30
10 20 30
10 20 30 

From my codes, I will be adding/summing the numbers from index[0][0] with index1 and index[2][2] USING POINTERS which will compute to 60. However, when I build and run, it returns computation of the memory address instead. Anyone can explain the problem here? (I'm new to C programming and pointers)

void diagonals2D(int array[][SIZE], int rowSize, int colSize, int *sum)
{
    int count;
    *sum=0;

    for(count=0;count<SIZE;count++)
    {
        (*sum)+=*(array+count+count);
    }

}

enter image description here

Upvotes: 1

Views: 3901

Answers (3)

arup nath
arup nath

Reputation: 37

As the given problem,you should use the following code.

for(count = 0; count < size; count++)
   sum=*( *( array + count ) + count);

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

The first parameter is adjusted to

int ( *array )[SIZE]

that is it is a pointer.

So the expression array + count also has the type int ( * )[SIZE]. To get the corresponding "row" of the array you have to dereference the pointer

*( array + count )

In this case you will have an object of the type int[SIZE] that in turn in the expression

*( array + count ) + count

is implicitly convered to the type int *.

Now dereferencing the whole expression you will get the target element

*( *( array + count ) + count )

It is better to declare the function as having the parameter of the variable length array.

Here is a demonstration program

#include <stdio.h>

void diagonals2D( long long int *sum, size_t n, int a[n][n] )
{
    *sum = 0;

    for ( size_t i = 0; i < n; i++ )
    {
        *sum += *( *( a + i ) + i );
    }
}

#define N   3

int main(void) 
{
    int a[][N] =
    {
        { 10, 20, 30 },
        { 10, 20, 30 },
        { 10, 20, 30 }      
    };

    long long int sum;

    diagonals2D( &sum, N, a );

    printf( "sum = %lld\n", sum );

    return 0;
}

Its output is

sum = 60

Upvotes: 3

magicleon94
magicleon94

Reputation: 5172

That array+count+count is not equivalent to array[count][count], that is what you need to achieve.
The best way you could achieve it is the cleaner array[count][count] but if you want to stick with pointers arithmetic from a learning point of view (again, this is bad for readability and debugging) you should access the element this way:

(*sum)+=*(*(array+count)+count);

This way you add count to the base pointer array, memory location of the base address of the countth row. It's a pointer to a pointer.

Dereferencing it will give you the base address of the row.

Adding count to the base pointer for the row will give you the address of the countth element of the row, and dereferencing it will give you the value of the element.

See the code here

Upvotes: 0

Related Questions