Thread: passing 2d arrays to functions

  1. #1
    Registered User
    Join Date
    Jul 2009
    Location
    Croatia
    Posts
    272

    passing 2d arrays to functions

    Is there a way to pass a 2d array to a function without the function knowing how many elements each row has?

    If not, i'm interested about what does "inverting" a 2d array means?

    Replacing first row with the last one, etc?

    Anyway, this is the code.

    Code:
    #include <iostream>
    
    using namespace std;
    
    void invert(char array[][3])
    {
          size_t rows = sizeof(array) / sizeof(array[0]);
          size_t columns = sizeof(array[0]);
          for(int i = 0, k = rows; i < rows; i++, k--)
             for(int j = 0; j < columns; j++) {
                 char temp = array[i][j];
                 array[i][j] = array[k][j];
                 array[k][j] = temp;
             }
    }
    
    int main()
    {
          char array[2][3] = { 'd', 'a', 'e', 'l', 'o', 'm' };
          cout << sizeof(array) << endl;
          cout << sizeof(array[0]) << endl;
          invert(array);
          for(int i = 0; i < 2; i++)
             for(int j = 0; j < 3; j++)
                cout << array[i][j];
          
          return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > Is there a way to pass a 2d array to a function without the function knowing how many elements each row has?
    No there isn't.

    So you need to do this instead:
    invert( array, sizeof(array)/sizeof(array[0]) );
    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. Passing Arrays to Functions...
    By txcs in forum C++ Programming
    Replies: 4
    Last Post: 04-22-2009, 10:36 AM
  2. passing structure arrays to functions?
    By bem82 in forum C Programming
    Replies: 3
    Last Post: 10-30-2006, 06:17 AM
  3. Passing arrays to functions?
    By gibbofresco in forum C++ Programming
    Replies: 6
    Last Post: 09-27-2006, 11:10 AM
  4. passing 2dimensional arrays to functions
    By owi_just in forum C Programming
    Replies: 1
    Last Post: 04-25-2005, 08:08 AM
  5. passing arrays through functions
    By Ecko in forum C++ Programming
    Replies: 4
    Last Post: 04-08-2003, 08:21 PM