Thread: 2 dimensional array as a function parameter

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    39

    2 dimensional array as a function parameter

    How does one pass a 2 dimensional array to a function and modify it in the function. I thought I knew this.

    For example a function that modifies a one dimensional array is declared as
    Code:
    void do_something ( double array[]);
    
    // and I can call it  with
    do_something(array); // for some
    double array[10];
    Now for an array with 2 rows and 3 columns I have
    Code:
    double array[2][3];
    
    //define function that takes this as parameter 
    do_something(double array[][3]);
    
    // dope. How do I call do_something???
    
    do_something(array);  // gives wrong answer

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Specify both dimensions, and pass the name of the array:
    Code:
    void foo( type array[D1][D2] );
    ...
    type array[D1][D2];
    foo( array );

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    double array[2][3];
    
    //define function that takes this as parameter 
    do_something(double array[][3]);
    
    // dope. How do I call do_something???
    
    do_something(array);  // gives wrong answer
    You need to post an actual example showing how it goes wrong for you, because this is exactly how you would do it.
    I suspect there is some other mistake.

    The left-most dimension is optional in the array parameter declaration.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array of struct as function parameter
    By rotger in forum C Programming
    Replies: 12
    Last Post: 11-11-2010, 02:33 PM
  2. Passing an array to a function as a parameter
    By boxden in forum C Programming
    Replies: 1
    Last Post: 03-13-2010, 09:35 AM
  3. array in function parameter declaration
    By DyingSoul in forum C Programming
    Replies: 11
    Last Post: 02-15-2009, 10:12 AM
  4. 2D array as function parameter
    By killer7 in forum C Programming
    Replies: 7
    Last Post: 08-20-2008, 02:51 AM
  5. Array initializing to a function parameter
    By JulleH in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2005, 07:56 AM