简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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