2D matrix pointers regarding functions

This is a discussion on 2D matrix pointers regarding functions within the C Programming forums, part of the General Programming Boards category; Hey this is my code, i want to seperate matrix printing and intialisation into functions as shown (and get then ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    18

    Question 2D matrix pointers regarding functions

    Hey this is my code, i want to seperate matrix printing and intialisation into functions as shown (and get then out of main)
    however I can't get it to work. I am able to pass 1D arrays but i can't work out 2D matrices

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_CUSTOMERS 100
    #define MAX_PRODUCTS 100
    
    void printMatrix( int matrix[][], int rows, int cols )
    { int n, m;
      /* Print matrix to check it worked */
      for( n=0; n<rows; n++ )
         { printf( "\n" );
           for ( m=0; m<cols; m++ )
            { printf(" %d", matrix[n][m] ); }
         }
         printf( "\n" );
      return;
    }
    
    void initialiseMatrix( int matrix[][] )
    {  int n, m;
       /* Set all values to -1 to indicate NOT valid */
       for( n=0; n<100; n++ )
        { for ( m=0; m<100; m++ )
           { matrix[n][m]=0; }
        }
       return;
    }
    
    int main()
    {
       int matrix[MAX_CUSTOMERS][MAX_PRODUCTS];
       initialiseMatrix( matrix );
       printMatrix( matrix, 100, 100 );
       return 1;
    }
    Thanks

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    > void printMatrix( int matrix[][], int rows, int cols )
    You need to specify all the minor dimensions.

    Eg.
    void printMatrix( int matrix[][MAX_PRODUCTS], int rows, int cols )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structs, pointers and functions
    By osici in forum C Programming
    Replies: 2
    Last Post: 04-29-2009, 12:35 AM
  2. 2d array of object pointers
    By Potterd64 in forum C++ Programming
    Replies: 17
    Last Post: 07-20-2006, 01:27 PM
  3. 2D Array of Pointers
    By Slavakion in forum C++ Programming
    Replies: 12
    Last Post: 03-31-2004, 04:05 PM
  4. Pointers, arrays , functions
    By sballew in forum C Programming
    Replies: 19
    Last Post: 09-16-2001, 11:12 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21