Mahi
Mahi

Reputation: 593

Why does this code assign space (' ') to specific elements of a character array?

I have this following program:

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

int main()
{
    char name[50],fname[50],sname[50],lname[50];
    int i,j,k;
    printf("First Name:");
    gets(fname);
    printf("sname:");
    gets(sname);
    printf("lname:");
    gets(lname);

    for(i=0;fname[i]!='\0';i++)
        name[i]=fname[i];
    name[i]=' ';

    for(j=0;sname[j]!='\0';j++)
        name[i+j+1]=sname[j];
    name[i+j+1]=' ';

    for(k=0;lname[k]!='\0';k++)
        name[i+j+k+2]=lname[k];
    name[i+j+k+2]=' ';

    printf("Concatenation is %s",name);
}

I'm confused as to why there is a space assigned in name[i]=' ' and name[i+j+1]=' ' and name[i+j+k+2]=' ' in this program.

If I execute with these, then I'm only getting concatenation, but if I remove them, I'm getting only the string of fname and not a concatenation of all.

Upvotes: 1

Views: 2688

Answers (1)

Michelle
Michelle

Reputation: 2900

The key here is that a null character and ' ' (the space character) are not the same. A null character is that '\0' character your for loops are checking for, a.k.a. the end of the string. A space is just a space, inserted between the parts of the name (think about "JamesEarlJones" vs "James Earl Jones" - you definitely want spaces).

It looks like either:

  • by default your arrays are initialized with null characters, which means if you don't assign a value to an element, it'll be '\0' (although this shouldn't be relied upon), or
  • you've got some awfully coincidental placement of null characters going on in the existing memory (there happens to be one after whatever length(s) of first name(s) and full names you've been trying).

If you skip an index when filling the name array (the +1 and +2 in your indices), you're leaving an element as the default/existing value ('\0'). If you don't print a space there, when printing out name, it'll hit a null character after the characters from fname and think that's the end of the string. If you include the lines that add space characters (not the same thing as '\0'), it sees the spaces, prints them, and keeps going.

Upvotes: 8

Related Questions