Method Call with Matrix Parameters

Asked

Viewed 123 times

3

I’ve always created vector methods using:

void exemplo(int vetor[], int qtd){  
// Código...  
// ...  
}  

And I never had problems, but I’m trying the same with matrices and I get an error

void exemplo(int matriz[][], int lin, int col){  
// Código...  
// ...  
}

The mistake is:

array type has incomplete element type

Follow an image with the code

inserir a descrição da imagem aqui

What’s the matter?

1 answer

2


In C arrays do not really exist. Deep down they are pointers.

When to access an element matriz[i] you’re actually doing *(matriz + i).

In a array multidimensional matriz[i][j] is making *(matriz + i * dimensao + j). What is the value of dimensao there? There is no way to know how you are using it. Multiplication is necessary to get the displacement. A dimension is a grouping of elements. To access them you need to know how many elements have in one of the dimensions. The other is not necessary to know.

If you change the parameter to int matriz[][3] then you’ll be doing *(matriz + i * 3 + j). You can specify the size of the two dimensions if you want: int matriz[3][3].

An example:

#include<stdio.h>
void print(int matriz[][3], int lin, int col) {
    for (int i = 0; i < lin; i++) {
        for (int j = 0; j < col; j++) printf("%d, ", matriz[i][j]);
    }
}

int main() {
    int a[3][3] = {{0}};
    print(a, 3, 3);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

One solution is to use pointer instead of array. Then you control access to the elements at hand:

#include<stdio.h>
#include <stdlib.h>
void print(int *matriz, int lin, int col) {
    for (int i = 0; i < lin; i++) {
        for (int j = 0; j < col; j++) printf("%d, ", *(matriz + i * col + j));
    }
}

int main() {
    int * a = malloc(9 * sizeof(int));
    print(a, 3, 3);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I think I got it. I will test here before class, but I would really like to access a row and column of the matrix using pointer, for example I want to access matrix[4][2]. How would I do that using pointers? I don’t know if you’ll understand what I mean, but thank you!

  • The way I showed you in the answer.

  • Ah ok. Thanks for the help. Have a good day

  • In C there are arrays yes: char *p; char a[32]; sizeof(p) != sizeof(a); Is it true to say that arrays decaem pointer.

Browser other questions tagged

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