nickb
nickb

Reputation: 3

Counting the amount of times a number appears in a 2D array C

I am trying to count the amount of times a number appears in a 2D array, but when I try and print values it starts giving me wrong numbers after the first element. I am trying to figure this out for a sudoku project I have, but I am posting different source code so I can figure out why this is happening.

#include <stdio.h>

int main() {
    int i, j, k;
    char check[10];
    char puzzle[6][10] = {
        { 1, 1, 3, 4, 4, 4, 5, 9, 2, 7 },
        { 9, 9, 8, 8, 8, 8, 8, 6, 9, 5 },
        { 1, 1, 3, 4, 4, 4, 5, 9, 2, 7 },
        { 9, 9, 8, 8, 8, 8, 8, 6, 9, 5 },
        { 1, 1, 3, 4, 4, 4, 5, 9, 2, 7 },
        { 9, 9, 8, 8, 8, 8, 8, 6, 9, 5 }
    };

    for (i = 0; i < 6; i++) {
        for (j = 0; j < 10; j++) {
            check[puzzle[i][j]]++;
        }
    }
    for (k = 1; k < 10; k++) {
        printf("check[%d] = %d\n", k, check[k]);
    }
    return 0;
}

OUTPUT:

check[1] = 6
check[2] = -101
check[3] = -6
check[4] = -56
check[5] = 101
check[6] = 2
check[7] = -126
check[8] = 15
check[9] = 12
Program ended with exit code: 0

Upvotes: 0

Views: 772

Answers (1)

bigwillydos
bigwillydos

Reputation: 1371

I am trying to count the amount of times a number appears in a 2D array, but when I try and print values it starts giving me wrong numbers after the first element.

The values in the array check that you are incrementing are non-zero because the array is never initialized.

This line:

char check[10];

Needs to be this:

char check[10] = {0};

Upvotes: 2

Related Questions