Show toolbar

2013年7月10日 星期三

Passing two-dimensional array to a function using pointer

標題:使用指標傳入函式的方式進行多維陣列的處理
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
using namespace std;

// 陣列指標位址, 行數, 列數, 乘值
void multiply(float *matrix, int rows, int columns, float num)
{
    int i = 0, j = 0;
    for(i=0;i<rows;i++)
    {
        for(j=0;j<columns;j++)
        {
            *matrix *= num;
            matrix++;
        }
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    const int m = 3, n = 4;
    int i = 0, j = 0;
    float matrixA[m][n] = { //3x4矩陣
        {1, 2, 3, 4},
        {0, 1, 0, 0},
        {0, 0, 1, 0}
    };
    
    //傳入matrixA的記憶體起始儲存位址以進行處理
    multiply(&matrixA[0][0], m, n , 5);

    //印出二維陣列資料
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            cout << matrixA[i][j] << "\t";
        }
        cout << endl;
    }
    return 0;
}

說明:
將陣列初始位址及陣列大小傳入函式,並在函式中針對指標內容進行運算操作。

沒有留言:

張貼留言