Passing 2-D array as argument

后端 未结 6 850
误落风尘
误落风尘 2020-12-31 14:03

I am trying to pass a 2-d array to a function which accept a pointer to pointer. And I have learnt that a 2-d array is nothing a pointer to pointer(pointer to 1-D array). I

相关标签:
6条回答
  • 2020-12-31 14:32

    declaration of ‘array’ as multidimensional array must have bounds for all dimensions except the first So you have to give

    array[][size] //here you must to give size for 2nd or more 
    

    For passing the array in function , array is not a pointer to a pointer but it's pointer to an array so you write like this

    fun(int (*array)[])
    

    Here if you miss the parenthesis around (*array) then it will be an array of pointers because of precedence of operators [] has higher precedence to *

    0 讨论(0)
  • 2020-12-31 14:33

    Why don't use std::vector instead of "raw" arrays. Advantages:
    1. It can dynamically grow.
    2. There is no issues about passing arguments to the function. I.e. try to call void myFuntion(int array[SIZE1][SIZE2]); with array, that has some different sizes not SIZE1 and SIZE2

    0 讨论(0)
  • 2020-12-31 14:37

    Another templated solution would be:

    template<int M, int N>
    void myFunction(int array[N][M])
    {
    }
    
    0 讨论(0)
  • 2020-12-31 14:39
    #include<iostream>
     void myFuntion(int arr[3][4]);
    int main()
      {
      int array[3][4]= {{1,2,3,4},{5,6,7,8},{10,11,12,13}};
     myFuntion(array);
      return 0;
     }
       void myFuntion(int arr[3][4])
       {
    
       }
    

    http://liveworkspace.org/code/0ae51e7f931c39e4f54b1ca36441de4e

    0 讨论(0)
  • 2020-12-31 14:46

    You should at least specify the size of your second dimension.

    int array[][5] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 10, 11, 12, 13 } };
    

    There is also an error which is often repeated. To pass a 2D array as argument, you have to use the following types:

    void myFuntion(int (*array)[SIZE2]);
    /* or */
    void myFuntion(int array[SIZE1][SIZE2]);
    
    0 讨论(0)
  • 2020-12-31 14:48
      void myFunction(int arr[][4])
    

    you can put any number in the first [] but the compiler will ignore it. When passing a vector as parameter you must specify all dimensions but the first one.

    0 讨论(0)
提交回复
热议问题