簡體   English   中英

使用雙指針創建函數進行矩陣運算

[英]Use double pointer to Create a function to do matrix operation

我正在嘗試創建一個包含一些功能的庫,例如創建矩陣,進行加,減,轉置和求逆矩陣,並且我需要使用雙指針。一開始,我編寫了這段代碼來分配矩陣,但似乎不起作用我不知道問題出在哪里

#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);

}  

很多問題。

  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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM