Thread: Proper way to pass in 2d array to function?

  1. #1
    Registered User
    Join Date
    Oct 2010

    Proper way to pass in 2d array to function?

    Say you have char arr[10][10] and you want to pass it to a function as is. How do you declare the function parameter? I want to be able to pass in a 2d array of arbitrary size, I don't want to fix the row OR the column size in the function definition. Thanks

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    You can't just make an empty-sized array:
    void cannotdothis( type bad[][] );
    You could fake it I suppose somehow, with a void pointer. Or you could just make it so you dynamically allocate it:
    type **makearray( size_t x, size_t y ) {
        ...allocate space...
        return it;
    Hope is the first step on the road to disappointment.

  3. #3
    Join Date
    Aug 2010
    somewhere in this universe
    Use the variable-length arrays for C99:
    type func(int rows, int cols,type array[rows][cols])

    or if you use dynamic array, then:

    type func(type **array, int rows, int cols)
    for the dynamic array, you can't pass in the static array, however.

    void func( int ** array, int rows, int cols)
    int arr[10][10] = { .....};
    func(arr, 10,10) // would not work.
    Last edited by nimitzhunter; 12-06-2010 at 11:28 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM