首页 > 解决方案 > 使用双指针创建函数进行矩阵运算

问题描述

我正在尝试创建一个库,其中包含一些函数,例如创建矩阵、添加、子、转置和反转矩阵,我需要使用双指针在开始时,我编写这段代码来分配矩阵,但它似乎不起作用我不知道问题出在哪里

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

static double P[4][4]={ { 1,   0,   0,   0},
                        { 0,   1,   0,   0},
                        { 0,   0,   1,   0},
                        { 0,   0,   0,   1}                       
                      };
double **P_M;
void show_matrix(int n,int m,double **matrix)
{
    int i,j;
    printf("\n The matrix is:\n");
    for (i=0;i<n;i++)
    {
        for (j=0;j<m;j++);
        printf(" \t",&matrix[i][j]);
        printf("\n");
    }
}

double matrix( int n, int m, double **matrix)
{
    int row;
    /*  allocate N 'rows'. */
    matrix = malloc( sizeof( double* ) * n );
    /*  for each row, allocate M actual doubles. */
    for( row = 0; row < n; row++ )
    matrix[ row ] = malloc( sizeof( double ) * m );

}

void main()
{
    int i, j;
    matrix(4,4,P_M);    
    for(i=1; i<5; i++)
            for(j=1; j<5; j++)
                P_M[i][j] = P[i-1][j-1];    
    //show_matrix(4,4,P_M);

}  

标签: cpointersdouble

解决方案


很多问题。

  1. 超出范围 - 因为索引从零开始。
  2. printf(" \t",&matrix[i][j]);->printf("%lf \t",matrix[i][j]);
  3. double matrix( int n, int m, double **matrix)->如果需要,最后double **matrix( int n, int m, double ***matrix)在函数 + 中进行适当的更改。return *martix;否则作废。叫它matrix(4,4,&P_M);

可能还有更多我没有注意到的。*** 指针很傻,不需要将地址传递给指针。

double **matrix(int n, int m)
{
    int row;
    double **array;
    /*  allocate N 'rows'. */
    if (!(array = malloc(sizeof(double*) * n)))
    {
        return NULL;
    }
    /*  for each row, allocate M actual doubles. */
    for (row = 0; row < n; row++)
        if (!(array[row] = malloc(sizeof(double) * m)))
        {
            //do something if malloc failed - for example free already allocated space.
            return NULL;
        }
    return array;
}

主要是 P_M = matrix(4,4);


推荐阅读