Construct an array through a vector

Asked

Viewed 102 times

2

I put nine digits in the vector but my matrix comes out with random numbers, I would like my matrix to come out with the numbers that are in the vector below my code:

#include <stdio.h>
#include <locale.h>

int vetor [9];
int matriz [3][3];
int i=0, lin=0, col=0, k=0;

main(){
    setlocale(LC_ALL, "");
    printf("Digite 9 número para uma matriz \n" );
    for(i=0;i<9;i++){
        scanf("%i", &vetor[i]);
    }
    for(lin=0;lin<3;lin++){
        for(col=0;col<3;col++){
            matriz[lin][col] = vetor[k];
            k++;
            printf("%i\t", &matriz[lin][col]);
        }printf("\n");
}
}

What I’m doing wrong?

1 answer

4


The main reason for the problem is that you are taking the address of the matrix to print. So to solve just take out the operator & in the argument of printf(). The operator is required to scanf() just to pass a reference, in printing this is not necessary, so the parameter is not expecting one. I gave an improved overall, but can avoid the nested loop too, I preferred not to move too much to hinder:

#include <stdio.h>
int main() {
    int vetor [9];
    int matriz [3][3];
    printf("Digite 9 número para uma matriz \n" );
    for (int i = 0; i < 9; i++) scanf("%i", &vetor[i]);
    for (int lin = 0, k = 0; lin < 3; lin++) {
        for (int col = 0; col < 3; col++, k++) {
            matriz[lin][col] = vetor[k];
            printf("%i\t", matriz[lin][col]);
        }
        printf("\n");
    }
}

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

  • Thanks bigown, I’m beginner in the language helped a lot!

Browser other questions tagged

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