Home > OS >  Why is this array bugging when I declare a matrix?
Why is this array bugging when I declare a matrix?

Time:10-27

That's the code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int linhas=0, col=0, num=0, i=0, pos1[100];
    int pos[100];
    scanf("%d %d %d", &linhas, &col, &num);

    int matriz[linhas][col];

    for(i=0; i<num;i  ){
       scanf(" %c%d", &pos[i], &pos1[i]);
    }

    for(i=0;i<num;i  ){
        pos[i] -= 97;
    }

    return 0;
}

It's quite simple, I declared 2 arrays, one to store the value of a char(pos[]), and the other to store integer values(pos1[]), and it works:D.

The thing is, if I declare a matrix ex: matrix[linhas][col], my code does not really store the values of a char, and if I take it off, it starts to store normally, also, it does not matter whether if I declare the matrix right after getting the rows and colums (linhas and col) or if I declare it at the end of the code. I don't know what the problem is, and I'd appreciate any hints.

CodePudding user response:

    int pos[100];
    scanf("%d %d %d", &linhas, &col, &num);

    int matriz[linhas][col];

    for(i=0; i<num;i  ){
       scanf(" %c%d", &pos[i], &pos1[i]);
    }

The %c format specifier will read in a character, but it requires the address of a character to read it into. You pass it the address of an int.

The simplest fix is to change pos to char pos[100];. Another possible fix is this:

    for(i=0; i<num;i  ){
       char c;
       scanf(" %c%d", &c, &pos1[i]);
       pos[i] = c;
    }
  • Related