【问题标题】:How to deliver a matrix to a function that prints it?如何将矩阵传递给打印它的函数?
【发布时间】:2021-12-23 11:08:54
【问题描述】:

我被要求获取一个 4x5 的矩阵并扫描每一行(这就是 for 方法的原因),然后打印前半部分,然后打印后半部分。

我相信问题不在函数内部,因为它们在数组上运行良好

当它尝试打印时,我得到随机数和零 -

0.000000
-107374176.000000
-107374176.000000
-107374176.000000
-107374176.000000
0.000000
-107374176.000000
-107374176.000000
-107374176.000000
-107374176.000000
0.000000
164582.031250
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
846674930930036512480361854271488.000000
0.000000
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void scanFloats(float** arr, int size); // scans the floats
void printFloats(float* arr, int size); // prints the floats

int main()
{
    float matrix[4][5];

    for (int i = 0; i < 4; i++)
    {
        scanFloats(matrix[i], 5);
    }

    printFloats(matrix, 10);
    printFloats(matrix + 10, 10);
}

void scanFloats(float** arr, int size)
{
    *arr = malloc(sizeof(float) * size);

    for (int i = 0; i < size; i++) {
        printf("Enter number\n");
        scanf("%f", (*arr) + i);
    }
}

void printFloats(float* arr, int size)
{
    for (int i = 0; i < size; i++)
    {
        printf("%f\n", *(arr + i));
    }
}

【问题讨论】:

  • 不要使用 malloc 数组已经分配了
  • 请在编译时出现警告:foo.c:14:20: warning: passing argument 1 of 'scanFloats' from incompatible pointer type ... foo.c:5:6: note: expected 'float **' but argument is of type 'float *',其他函数也一样。
  • 想一想:matrix[i]是什么类型
  • 我想了更多关于它提供了什么。 Matrix[i] 将提供我想要的地址+i,以单独扫描每一行。我怎样才能以正确的方式做到这一点?
  • 我会说试试printFloats(&amp;matrix[2][0], 10);,但即便如此,你还是在滥用数组,假装它不是二维的

标签: c function pointers matrix


【解决方案1】:

使用与您的数组相同的类型:

void printFloats(size_t rows, size_t cols, float arr[rows][cols]);

int main(void)
{
    float matrix[4][5] = {
        {1,2,3,4,5},
        {10,20,30,40,50},
        {100,200,300,400,500},
        {1000,2000,3000,4000,5000},
    };

    printFloats( 4, 5, matrix);

}

void printFloats(sizet rows, size_t cols, float arr[rows][cols])
{
    for (size_t r = 0; r < rows; r++)
    {
        for (size_t c = 0; c < cols; c++)
        {

            printf("%8.2f", arr[r][c]);
        }
        printf("\n");
    }
}

与扫描功能相同:

void scanFloats(size_t rows, size_t cols, float arr[rows][cols])
{

    for (size_t r = 0; r < rows; r++)
    {
        for (size_t c = 0; c < cols; c++)
        {
            if(scanf("%f", &arr[r][c]) != 1)
            {
                 /* handle scan error */
            }
        }
    }
}

https://godbolt.org/z/z8nxo1jhe

【讨论】:

  • 不错的答案。无关:scanf("%f", &amp;arr[r][c]); 没有任何检查是坏的,坏的,坏的
  • @4386427 这不是真正的代码,仅演示如何传递数组。添加其他任何东西都没有意义
  • 不同意,但还是要UP
  • 无法检查scanf返回的值是一个非常常见的错误。未能证明正确使用会传播错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
相关资源
最近更新 更多