Passing a 2-dimensional array as an argument

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thatos
    New Member
    • Aug 2007
    • 105

    Passing a 2-dimensional array as an argument

    I would like to know how do I pass a 2-dimensional array as an argument to a funtion, if I will only know the size in runtime.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Then you pass a pointer to the first member plus the 2 sizes to your function.

    Within your function you treat the array as a single dimensioned array and use the 2 sizes plus the 2 indexes to calculate the index into that array to use.

    e.g.

    Code:
    static void function2(int *, int, int);
    
    void function1(void)
    {
    #define MAX_X 10
    #define MAX_Y 10
    
        int array [MAX_Y][MAX_X];
    
        function2(array, MAX_X, MAX_Y);
    }
    
    static void function2(int *array_ptr, int x_size, int y_size)
    {
        /* Accessing the 3rd (index 2) element of the 4th row (index 3) */
    
        int result = 0;
    
        /* Check that the indexes are in range for the array */
        if (3 < y_size && 2 < x_size)
        {
            result = array_ptr[x_size * 3 + 2];
        }
    }
    Note: example code not compiled.

    This is more or less the calculation that the code produced by the compiler does anyway when you access an array although the compiler produced code does not bounds check the array indexes.

    If you happen to know one of the dimensions at compile time this can be simplified a lot by using the right pointer but you have said you don't.

    And 1 final and very important note, this is how you would do it in C. If you are using C++ you should not be using pointers/arrays, you should be using a container from the C++ STL, most probably vector. Using STL containers removes all this kind of problem as all the information and methods required to access the data is carried in the vector class so you can just pass a reference to your vector object.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      Look here: Arrays Revealed.

      Comment

      • thatos
        New Member
        • Aug 2007
        • 105

        #4
        Thanks for your help. Will it make it an easy if I new the maximum dimensions of that array?

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          No the maximum possible dimensions are not relevant, only the actual dimension at run time.

          Comment

          Working...