简体   繁体   English

如何将矩阵传递给打印它的函数?

[英]How to deliver a matrix to a function that prints it?

I been asked to take a matrix of 4x5 and scan each row (that's why the for method) and then print the first half, and then teh second half.我被要求取一个 4x5 的矩阵并扫描每一行(这就是 for 方法的原因),然后打印前半部分,然后打印后半部分。

I believe the problem isn't inside the function because they work fine on arrays我相信问题不在函数内部,因为它们在数组上工作正常

When it's trying to print I get random numbers and zeros -当它尝试打印时,我得到随机数和零 -

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

Use same type as your array is:使用与您的数组相同的类型:

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

Same with scan function:与扫描功能相同:

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++)
        {
            scanf("%f", &arr[r][c]);
        }
    }
}

https://godbolt.org/z/z8nxo1jhe https://godbolt.org/z/z8nxo1jhe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM