Traversing Two Dimensional Array

How come Line 1 and Line 2 have more than ten x(s) when the loop should end at ten given the condition of ii < 10?

I am trying to understand how these two dimensional arrays work, any advice is appreciated.

#include <stdio.h>
int main()
{
    char name[3][10];

    for(int i = 0; i < 3; i++){
        for(int ii = 0; ii < 10; ii++){
            name[i][ii] = 'x';
        }
    }


    printf("Line 1: %s.\n", name[0]);

    printf("Line 2: %s.\n", name[1]);

    printf("Line 3: %s.\n", name[2]);


    return 0;
}

FIX:

Thanks to everyone's comments I managed to fix the code. The problem was that I was not reserving one space for the NULL terminator at the end of the array. Since I wanted ten x(s), the solution is to increase the size of the two dimensional array so that it has space for the NULL terminators.

#include <stdio.h>
int main()
{
    char name[4][11];

    for(int i = 0; i < 3; i++){
        for(int ii = 0; ii < 10; ii++){
            name[i][ii] = 'x';
        }
    }


    printf("Line 1: %s.\n", name[0]);

    printf("Line 2: %s.\n", name[1]);

    printf("Line 3: %s.\n", name[2]);


    return 0;
}


Read more here: https://stackoverflow.com/questions/66994693/traversing-two-dimensional-array

Content Attribution

This content was originally published by Rivf at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: