Adrian Adrian - 7 days ago 5
C Question

C: issue with printing 2d array

I'm working on my C code, and got a problem with printing my 2d array. Instead of printing one string at the time, it prints the entire array from the asked point.

As an example, the input is, "Dog", "Cat", "Hat". Then it would print out:

DogCatHat
CatHat
Hat


This is what my code is suppsoed to do: It reads from a file. It creates an array of char arrays. Where each char array has 30 chars in them, read from file one char at the time. Then it prints out one char array per line.

This is what the code looks like:

char fname[] = "folder/text.txt";
char arry[30][30];
FILE *file;

file = fopen(fname, "r");
for(int x=0; x<30; x++){
for(int i=0; i<30; i++){
arry[x][i] = fgetc(file);
}
}

fclose(file);
for(int i=0; i<30; i++){
printf("%s\n", arry[i]);
}


Most likely I have just made an obvious mistake, but I'm not able to find it. So please help.

Answer

I think strings in file are not null terminated. So you need to put null character at the last character of the array.

char arry[30][30]

for(int x=0; x<30; x++){
    for(int i=0; i<29; i++){  //You can write 28 characters + '\0'
        arry[x][i] = fgetc(file);
    }
    arry[x][29] = '\0';
}
for(int i=0; i<30; i++){
    printf("%s\n", arry[i]);
}
Comments