Proper way to pass in 2d array to function?

This is a discussion on Proper way to pass in 2d array to function? within the C Programming forums, part of the General Programming Boards category; Say you have char arr[10][10] and you want to pass it to a function as is. How do you declare ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    14

    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
    Posts
    14,826
    You can't just make an empty-sized array:
    Code:
    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:
    Code:
    type **makearray( size_t x, size_t y ) {
        ...allocate space...
        return it;
    }
    Quzah.
    Hope is the first step on the road to disappointment.

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

    or if you use dynamic array, then:

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

    Code:
    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 10: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, 12:03 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM

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