Search code examples
cmultidimensional-arraynested-loops

I can't seem to fix this issue about nested for loops + 2d arrays


this is the code I am having a problem with 1 2 the code:

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


int main(){ 

    int i, j;
    int num[3][2] = { (1, 2),
                      (3, 4),
                      (5, 6)
                    };
    for(j = 0; j < 3; j++){
        for( i = 0; i < 2; i++ ){
            printf("%d, ", num[j][i]);
        }   printf("\n");
    }
    return 0;
}

guys I am watching this course of freecodecamp about the C language and the guy tutoring got this code right as it says in the console: 1, 2, 3, 4, 5, 6, and I typed the EXACT same code but still not working, I double- checked and everything, but nothing seems to work. 3


Solution

  • As @Oka said you need to use {} in the initializer. Also fixing formatting, separators, and localizing variables:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int num[3][2] = {
            {1, 2},
            {3, 4},
            {5, 6}
        };
        for(size_t j = 0; j < sizeof(num) / sizeof(*num); j++) {
            for(size_t i = 0; i < sizeof(*num) / sizeof(**num); i++ ) {
                printf("%d%s",
                    num[j][i],
                    i + 1 < sizeof(*num) / sizeof(**num) ? ", " : "\n"
                );
            }
        }
        return 0;
    }