C/C++ 二維數組

來源:互聯網
上載者:User

標籤:har   free   輸出   turn   names   sizeof   highlight   out   for   

使用C語言用到了二維數組

 1 #include <iostream> 2 #include <stdlib.h> 3 using namespace std; 4  5 void print_arr_fun1(int arr[][3], int row){ 6     for (int i = 0; i < row; ++i){ 7         for (int j = 0; j < 3; ++j) 8             cout << arr[i][j] << " "; 9         cout << endl;10     }   11 }12 13 void print_arr_fun2(int *arr, int row, int col){14     for (int i = 0; i < row; ++i){15         for (int j = 0; j < col; ++j)16             cout << *(arr + i * row + j) << " ";    17         cout << endl;18     }   19 }20 21 void print_arr_fun3(int **arr, int row, int col){22     for (int i = 0; i < row; ++i){23         for (int j = 0; j < col; ++j)24             cout << arr[i][j] << " ";   25         cout << endl;26     }   27 }28 29 int main(){30     const int row = 2;  //這裡是const31     const int col = 3;32     int arr1[row][col];33     for (int i = 0; i < row; ++i)34         for (int j = 0; j < col; ++j)35             arr1[i][j] = i * col + j;36 37     cout << "print_arr_fun1---------------------------" << endl;38     print_arr_fun1(arr1, row);39     cout << "print_arr_fun2---------------------------" << endl;40     print_arr_fun2((int*)arr1, row, col);41 42     cout << "print_arr_fun3---------------------------" << endl;43     int **arr2 = (int**)malloc(sizeof(int*) * row);44     //malloc45     for (int i = 0; i < row; ++i)46         arr2[i] = (int*)malloc(sizeof(int) * col);47     for (int i = 0; i < row; ++i)48         for (int j = 0; j < col; ++j)49             arr2[i][j] = i * col + j;50     print_arr_fun3(arr2, row, col);51 52     //free53     for (int i = 0; i < row; ++i)54         free(arr2[i]);55     free(arr2);56 57     return 0;58 }

輸出:

print_arr_fun1---------------------------0 1 2 3 4 5 print_arr_fun2---------------------------0 1 2 2 3 4 print_arr_fun3---------------------------0 1 2 3 4 5 

C/C++ 二維數組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.