Sparrow
Sparrow

Reputation: 305

Error in printing array of strings in C

I have a simple program to input the an array of 5 strings and output them. But the output is some what weird. The following is my code.

#include <stdio.h>

int main()
{
    char a[10][5];
    int i;
    for(i=0; i<5; ++i)
    {
        printf("\nEnter the name of %d st student:", i+1);
        fflush(stdout);
        gets(a[i]);
    }
    for(i=0; i<5; ++i)
    {
        printf("\n%s", a[i]);
        fflush(stdout);
    }
    return 0;
}

I gave the inputs as tom, john, peter, david and alan and I get the following output.

tom
john
peterdavidalan
davidalan
alan

What could be the problem?

Upvotes: 0

Views: 2065

Answers (2)

macfij
macfij

Reputation: 3209

just change your char a[10][5]; to char a[5][10];

you will have then 5 rows with 10 columns each. current setting of a lets you hold 10 inputs of 4 characters long (since you need a \0 character at the end of string).

C doesn't check for boundaries and multidimensional arrays are stored continguously in memory. therefore, with input longer than 4 characters you are overflowing the current storage for your char array and writing to next row.

Adam D. Ruppe mentioned that printf() will be printing chars to screen until it meets the \0 terminator. see that you are:

  • loosing terminator with "peter" input
  • loosing terminator with "david" input

hence you get the output "peterdavidalan". now i think you can figure out from where "davidalan" output came.

Upvotes: 2

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25595

The C array syntax is pretty confusing IMO - it means the opposite of the way I typically read it... and it looks like you made that mistake too.

Your array has ten slots of strings 4 chars each (it isn't 5 because each string in C must end with a 0 character). So when you enter peter, instead of comfortably fitting in a 10 char buffer, it overflows a 5 char buffer, saving over one of the characters saved previously.

Without the 0 terminator, printf will just keep going, and thus write the other names too.

Upvotes: 7

Related Questions