Search code examples
cfunctionfor-loopmatrixnested-loops

Function for defining and printing all the elements of a matrix


I'm studying functions in C, and I wanted to create a function to set all the elements of a matrix with the same value, and then print the matrix with another function. Is it possible? This is the code I wrote[EDITED]:

#include <stdio.h>
#include <stdlib.h>
#define x 79
#define y 24

int def_matrice(int matrice[y][x], int valore);
int print_matrice(int matrice[y][x]);

int main()
{
    int  i = 0, j = 0, matrice[y][x];

    for(i = 0; i < y; i++)
    {
        for(j = 0; j < x; j++)
        {
            matrice[i][j] = 32;
        }
    }

    for(i = 0; i < y; i++)
    {
        for(j = 0; j < x; j++)
        {
            printf("%c", matrice[i][j]);
        }
        printf("\n");
    }

    def_matrice(matrice[y][x], 89);
    print_matrice(matrice[y][x]);

    return 0;
}

int def_matrice(int matrice[y][x], int valore)
{
    int i = 0, j = 0;
    for(i = 0; i < y; i++)
    {
        for(j = 0; j < x; j++)
        {
            matrice[i][j] = valore;
        }
    }
    return 0;
}

int print_matrice(int matrice[y][x])
{
    int i = 0, j = 0;
    for(i = 0; i < y; i++)
    {
        for(j = 0; j < x; j++)
        {
            printf("%c", matrice[i][j]);
        }
        printf("\n");
    }
    return 0;
}

But when I try to compile, I get the following errors[EDITED]:

|30|error: passing argument 1 of 'def_matrice' makes pointer from integer without a cast|
|6|note: expected 'int (*)[79]' but argument is of type 'int'|
|31|error: passing argument 1 of 'print_matrice' makes pointer from integer without a cast|
|7|note: expected 'int (*)[79]' but argument is of type 'int'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Solution

  • Fix your prototypes (at function declaratio and function definition):

    int def_matrice(int matrice[y][x], int valore)
    int print_matrice(int matrice[y][x])
    

    Then fix your function calls:

    def_matrice(griglia, 89);
    print_matrice(griglia);
    

    Then you need declarations for i and j in def_matrice and in print_matrice.

    Then def_matrice and print_matrice have parameter names matrice but the name griglia is used in the functions.