Help in printing 2 d string array in c

I had trouble removing the last name because it prints twice. I just want it to print once. One print for every name of the array.

Sample output:
nameDoublesProblemC

Here is the code:

#include <stdio.h>

void print(char (*names)[3][5], int outer, int inner);

int main() {

    char name[][3][5] = {{"Dab", "Gel", "Rish"}, {"Ron", "Angel", "Layla"}};

    int outSize = sizeof(name)/sizeof(*name);
    int inSize = sizeof(*name)/sizeof(*(*name));

    //printf("\nOuter: %d", outSize);
    //printf("\nInner: %d", inSize);
    
    print(name, outSize, inSize);

    return 0;
}

void print(char (*names)[3][5], int outer, int inner) {
    for(int i=0; i < outer; i++) {
        printf("\n");
        for(int j=0; j < inner; j++) {
            printf("%-10s", *(*(names+i)+j));
        }
    }
}
char name[][3][5]

So if I am not mistaken, this means you are declaring an array of unknown size, containing arrays of 3 elements, containing character-strings of 5 characters, right?

Well there is the issue - C is using null-determined strings, meaning a string ends with a “\n” character. So a string with 5 non-null Characters (like “Angel”) needs a size of 6.
Because you only give it a size of 5, it’s not including the null-character and thus it’s not merely printing out the last name twice, it’s printing “AngelLayla” and “Layla” because when filling the memory with data, the “L” overrode the null-character, whereas the memory after Layla got a null written there and so far is just hasn’t been overritten, despite the fact it’s outside of the reserved memory.

At least, that’s my take on it.
Please tell if increasing the size of the strings does help.

2 Likes

Oh nice, it worked. I forgot about the null part. Thanks for the help :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.