本文分享了利用二维动态数组指针做矩阵运算的实现代码。
1. 头文件
// juzhen 2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdlib.h"
#include "windows.h"
#define OK 0
#define NG -1
typedef struct mat
{
int nRow; /* 行数 */
int nCol; /* 列数 */
int* pData; /* 指向矩??体的指? */
}MAT;
2. 程序代码
#include "stdafx.h"
#include "Matrix_cal.h"
/* Entity and initial matrix of the application matrix function */
int MATAlloc(MAT *pMat, int nRow, int nCol)
{
pMat->pData = (int *) malloc (nRow * nCol * sizeof(int) );
if(NULL == pMat->pData)
{
printf("Memary is error!\n");
return NG;
}
for(int i=0; i
{
for(int j=0; j
{
*(pMat->pData + i*nCol + j)=0;
}
}
pMat->nRow = nRow;
pMat->nCol = nCol;
return OK;
}
/* Release the memory space and reset the matrix data function */
void MATFree(MAT* pMat)
{
free(pMat->pData);
pMat->pData = NULL;
pMat->nRow = 0;
pMat->nCol = 0;
}
/* Import of matrix function */
int MATAssign (MAT* pMat1, const MAT* pMat2)
{
MATAlloc(pMat1, pMat2->nRow, pMat2->nCol);
for(int i=0; i < pMat1->nRow; ++i)
{
for(int j=0; j < pMat1->nCol; ++j)
{
*(pMat1->pData + i * pMat1->nCol + j) = *(pMat2->pData + i * pMat1->nCol + j);
}
}
return OK;
}
/* Matrix sum function */
int MATAdd(const MAT* pMat1, const MAT* pMat2, MAT* pMat3)
{
MATAlloc(pMat3, pMat1->nRow, pMat1->nCol);
if((pMat1->nRow == pMat2->nRow) && (pMat1->nCol == pMat2->nCol))
{
for(int i=0; inRow; ++i)
{
for(int j=0; jnCol; ++j)
{
*(pMat3->pData +