zoukankan      html  css  js  c++  java
  • C/C++ 二维数组

    使用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;  //这里是const
    31     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     //malloc
    45     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     //free
    53     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 
  • 相关阅读:
    【BZOJ1901】Dynamic Rankings(树套树,树状数组,主席树)
    【Vijos1222】等值拉面(DP)
    【Vijos1534】高性能计算机(DP)
    【POJ3321】Apple Tree(DFS序,树状数组)
    主外键约束
    java访问权限
    java2实用教程102小程序(分数计算和流水线计算
    java对象初级知识
    java第一天的疑问
    时间
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/7668061.html
Copyright © 2011-2022 走看看