c - 如何从函数中的矩阵指针赋予值属性

标签 c function pointers

我正在创建一个通过函数转置矩阵的代码。然而,当我运行此代码时,它会打印原始矩阵,但它会关闭而不打印转置矩阵。我几乎可以肯定问题出在转置函数内部的归因上,但我无法理解它。

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

//Here I create a function to transpose the matrix
//I receive a pointer to a double matrix
void transpose(double *matrix[][5], int size)
{
    //I create a second matrix
    double transposed[size][5];
    //I transpose the original matrix into the transposed matrix
    for (int i=0; i<=size-1; i++)
    {
        for (int j=0; j<=4; j++)
        {
            transposed[j][i] = *matrix[i][j];
        }
    }
    //I attribute the values from the transposed matrix to the original matrix
    for (int i=0; i<=size-1; i++)
    {
        for (int j=0; j<=4; j++)
        {
            *matrix[i][j] = transposed[i][j];
        }
    }

}

int main()
{
    //Here I create a matrix and ask for the user to type its values
    double matrix[5][5];
    for (int i=0; i<=4; i++)
    {
        for (int j=0; j<=4; j++)
        {
            printf("Position [%d][%d]", i+1, j+1);
            scanf("%lf", &matrix[i][j]);
        }
    }
    //I use the function
    //I print the matrix after using the function
    transpose(matrix, 5);
    printf("Transposed:\n");
    for (int i=0; i<=4; i++)
    {
        for (int j=0; j<=4; j++)
        {
            printf("%lf   ", matrix[i][j]);
        }
        printf("\n");
    }
}

最佳答案

有关“间接级别”的编译器警告应该已经提醒您了。该函数应该是

void transpose(double matrix[][5], int size)

和其他*星星也应该被删除。

transposed[j][i] = matrix[i][j];
...
matrix[i][j] = transposed[i][j];

<小时/> 旁白:你的循环控制限制不是惯用的。这个i<=size-1;更好的是 i<size; (并且可能是错误的)。

您对限制进行了硬编码,例如 j<=4目前尚不清楚这实际上是 5-1如果您使用过 j<5更明显的是它是相同的 5就像在数组维度中一样。

您是否应该决定将该维度替换为 #defineconst int值,你必须寻找 4以及 5 s。

关于c - 如何从函数中的矩阵指针赋予值属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58456307/

相关文章:

c++ - Windows 上最快的屏幕捕获方法

c - 如何从注册表中获取每个键和子键?

用于验证时间 00 :00 with regular expression 的 Javascript 函数

c - 如何重新启动程序而不保存其值 (C)

c++ - 将字母转换为整数,然后求字符串之和

c - valgrind - 地址是分配的大小为 16 的 block 之前的 2 个字节

javascript - 从函数内部更改全局变量

c++ - 一行中的最后一个数组元素和下一行中具有相同指针的第一个元素

C 重新分配错误 : malloc(): invalid size (unsorted)

c++ - 从 int 到 c 字符串 (const char*) 的转换失败