c - 使用双指针创建函数进行矩阵运算

标签 c pointers double

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

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

关于c - 使用双指针创建函数进行矩阵运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50315160/

相关文章:

java - 使用 JNI 从 Java 代码中检索字符串值的内存泄漏

c - 使用指针和字符串——一个字符如何变成一个整数?

c - IEEE 754 : is v *= -1 always guaranteed to be the same as v = -v?

从 C 函数更改 gtk_tree_selection 中的选定行

c - atan2f 使用 m32 标志给出不同的结果

arrays - 来自返回数组最大值的函数的 C 段错误

c# - 想知道为什么指针算法在 asp.net 中不起作用

c++ - 维度字符数组之外的额外垃圾值

objective-c - Objective C 数学

c# - 为什么解析后的 double 不等于假定具有相同值的初始化 double ?