Search code examples
arraysc

C suddenly messing up values in 2d array


My code:

int main(){
    int n;
    scanf("%d", &n);
    int a;
    int b;
    char inp;
    int zx;
    int zy;
    int tab[n][n];      
    for(a = 0; a < n ; a++){
        for(b = 0; b < n; b++){
            scanf("%c", &inp);          
            switch(inp){
                case 'a':
                    tab[b][a] = 6;
                    //printf("%d\n", tab[b][a]);
                    break;
                case 'b':
                    tab[b][a] = -1;
                    //printf("%d\n", tab[b][a]);
                    break;
                case 'c':
                    tab[b][a] = 9;
                    zx = b;
                    zy = a;
                    //printf("%d\n", tab[b][a]);
                    break;
            }
        }
    }
    for(a = 0; a < n ; a++){
        for(b = 0; b < n; b++){
            printf("%d ", tab[b][a]);
        }
        printf("\n");
    }   
    return 0;   
}

The idea is to replace the input map consisting of chars 'a', 'b', c' with their values in int map. a = 6, b = -1, c = 9.

so an input like

5
aacbb
ababa
aaaaa
aaabb
bbbbb

should output like

669-1-1
6-16-16
66666
666-1-1
-1-1-1-1-1

When I'm inputting values in 2d array everything seems ok. Everything is ok with commented printf values, however when I try to output the whole map it's like:

622671 6 6 9 -1
6 -485498561 6 -1 6
-1 6 564564 6 6
6 6 6 4541512341 -1
-1 -1 -1 -1 564231

which is clearly totally wrong. With linux I get a core dump instead of an output. I need an explanation why is this happening.


Solution

  • You don't have a default case in the switch, so when you don't handle the input value the array is uninitialized when you print it.

    The first time the loop runs, there is a '\n' that was left by the previous scanf(). The "%c" specifier does consume it, so your first time in the loop, the value was already supplied without asking you, and since you are not handling the '\n' in the switch, the corresponding array element is left uninitialized.

    Change

    scanf("%c", &inp)
    

    to

    scanf(" %c", &inp)
    

    and it will work as you expect it.

    And also, just in case add

    default:
        tab[b][a] = 0;
        break;
    

    to the switch, to prevent passing uninitialized values to printf().