Why can’t I pass a matrix as a parameter of a function in C?

Asked

Viewed 215 times

0

Dear friends, today I have come across a problem I cannot understand. When trying to pass an array as a parameter, I cannot access the values of the elements, I always access the memory addresses of the elements of the second line downwards. Why this occurs? Follow the code of my program that appeared error.

I used the master stdio library. h and the constant MAX

#include <stdio.h>
#define MAX 10

Call on main:

int mat[3][3] = {8, 0, 7, 4, 5, 6, 3, 10, 2};
verifica_quadrado_magico(mat, 3);

Body of function:

void verifica_quadrado_magico(int matriz[][MAX], int dim){
int i, j, somaDP = 0, somaDS = 0, somaL, somaC, somaL0 = 0;
int igual = 0;

for(i = 0; i < 3; i++){
    for(j = 0; j < 3; j++){
        printf("%i\t", matriz[i][j]);
    }
    printf("\n");
}
//Continua, mas até aqui já é o suficiente para entender meu problema

The screen output was this: Imagem passando a matriz como parâmetro

2 answers

2


You define MAX=10 and uses this value as the size of the secondary dimension in the argument matriz[][MAX], but its matrix has dimensions mat[3][3].

When the loop will jump line in the matrix, advance ten positions in memory and "drop off" variable.

  • Thank you for the explanation, my dear!

1

@Kahler already explained the problem, which is to have an incorrect size in the function parameter, but my answer shows how to solve leaving the dynamic size.

If you try to put matriz[dim][dim] directly in the function parameter, without changing anything else will not work and will get the following build error:

error: 'dim' undeclared here (not in a Function)

error: type of formal Parameter 1 is incomplete

In order for it to work, you also have to change the order of the parameters so that the dim come first, like this:

void verifica_quadrado_magico(int dim, int matriz[dim][dim]){

In your code there are also some things you should get right:

  • Must use the dim as a limit of for
  • Initialization of the matrix in the main must use {} for each line.

Simplified and working example:

#include <stdio.h>

void verifica_quadrado_magico(int dim, int matriz[dim][dim]){
    int i, j;

    for(i = 0; i < dim; i++){
        for(j = 0; j < dim; j++){
            printf("%i\t", matriz[i][j]);
        }
        printf("\n");
    }
}

int main(){
    int mat[3][3] = {{8, 0, 7}, {4, 5, 6}, {3, 10, 2}};
    verifica_quadrado_magico(3, mat);
}

Check it out at Ideone

  • Thank you, I’ll test this on my program.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.