Thread: Two dimensional arrays and pointers

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    9

    Two dimensional arrays and pointers

    I'm not understanding what's happening here.
    Two dimensional arrays and pointers-captura-de-pantalla-de-2019-04-16-10-21-50-png

    It seems that I'm feeding the function in the wrong way

    Code:
    #define LEN 4
    
    int sum_two_dimensional_array(const int a[][LEN], int n)
    {   
        const int *p;
        int sum = 0;
        
        for (p = &a[0][0]; p < &a[n-1][LEN-1]; p++)
            sum += *p;
        
        return sum;
    }
    
    int main(void)
    {
        int arr[3][LEN] = {{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 0, 3, 2}};
        
        printf("The sum is: %d\n", sum_two_dimensional_array(arr, 3));
        
        return 0;
    }
    It's just an exercises from a book. modify the function int sum_two_dimensional_array(const int a[][LEN], int n);
    Using pointers to eliminate the use of two for loops, variables i & j and the [ ] (which I dont know how can I write the for loop for twodim array without using the [ ] )
    Any explanation it's appreciate

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Maybe this is a better approach:

    Code:
    #include <stdio.h>
    
    #define LEN 4
    
    // n = number of "lines", m = number of "columns".
    // p pointer to the first element.
    int sum_two_dimensional_array ( const int *p, 
                                    int n, int m )
    {
      int sum = 0;
    
      // Points to next address beyond the array boundary.
      const int *q = p + m*n;
    
      while ( p < q )
        sum += *p++;
    
      return sum;
    }
    
    int main ( void )
    {
      int arr[][LEN] = {
        {1, 2, 3, 4}, 
        {1, 2, 3, 4}, 
        {1, 0, 3, 2}
      };
    
      printf ( "The sum is: %d\n", 
        sum_two_dimensional_array ( (const int *)arr, 
                                    3, 4 ) );
    
      return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing pointers to two-dimensional arrays of structs
    By dr.neil.stewart in forum C Programming
    Replies: 2
    Last Post: 09-07-2007, 10:25 AM
  2. Pointers and multi dimensional arrays
    By andrea72 in forum C++ Programming
    Replies: 5
    Last Post: 01-23-2007, 04:49 PM
  3. Pointers to multi dimensional arrays.
    By bartybasher in forum C++ Programming
    Replies: 2
    Last Post: 08-25-2003, 02:41 PM
  4. Array pointers to Multi-Dimensional Arrays
    By MethodMan in forum C Programming
    Replies: 3
    Last Post: 03-18-2003, 09:53 PM
  5. Hello all and pointers to multi-dimensional arrays
    By Mario in forum C++ Programming
    Replies: 16
    Last Post: 05-17-2002, 08:05 AM

Tags for this Thread