How to pass 2D array (matrix) in a function in C?

前端 未结 5 633
旧时难觅i
旧时难觅i 2020-11-22 01:31

I need to do this to persist operations on the matrix as well. Does that mean that it needs to be passed by reference?

Will this suffice?

void operate

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:11

         #include 
         using namespace std;
    
         void printarray(int *a, int c,int r)
         {
            for (int i = 0; i < r; i++)
            {
                for (int j = 0; j < c; j++)
                {
                    cout << "\t" << *(a + i*c + j) << "\t";  // a is a pointer refer to a 2D array
                }
            cout << endl << "\n\n";
            }
         }
    
         int main()
         {
             int array[4][4] = 
             {{1 ,2 ,3 ,4 },
              {12,13,14,5 },
              {11,16,15,6 },
              {10,9 ,8 ,7 }};
    
              printarray((int*)array,4,4);
              // here I use print function but u can use any other useful function like 
              //setArray((int *) array,4,4);
    
            return 0;
        }
    

提交回复
热议问题