1. 程式人生 > >二維陣列的動態申請空間並引數傳給函式

二維陣列的動態申請空間並引數傳給函式

說明:
1. 二維陣列動態建立
2. 把二維陣列作為引數傳遞給函式

參考程式碼:

#include <stdio.h>
#include <stdlib.h>

void func(int** pArray, int m, int n)
{
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
            printf("%d ", pArray[i][j]);
        printf("\n");
    }
}

int main()
{
    int
m = 10; int n = 10; int **p; //方法一:C++ //p = new int *[m]; //for (int i = 0; i < m; i++) // p[i] = new int[n]; //方法二:C //p = (int**)malloc(m * sizeof(int*)); //for (int i = 0; i < m; i++) // p[i] = (int*)malloc(n * sizeof(int)); //方法三: 申請一段連續空間 //int *temp = new int[m * n];
//p = new int *[m]; //for (int i = 0; i < m; i++) // p[i] = temp + i * n; //方法四: 方法三的另外一種寫法 p = new int *[m]; p[0] = new int[m * n]; for (int i = 1; i < m; i++) p[i] = p[i - 1] + n; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) p[i][j] = m * i + j; func(p, m, n); //for (int i = 0; i < m; i++)
// delete[] p[i]; //delete p; //for (int i = 0; i < m; i++) // free(p[i]); //free(p); }

執行結果:
這裡寫圖片描述