ritam bala
ritam bala

Reputation: 139

String Initialization in c

I am quite new to C programming so feel free to correct me, I insist. My basic understanding of strings in C is when we initialize a string a null character is automatically assigned at the end of the string and the null character cannot be read read or written, but is used internally only.

So when I create a string of size 4 as char str[3] and assign a word to it say "RED" and print it using puts function or printf("%s",str), I get an unusual output printed as RED(SMIILEY FACE)

I then again reduce the size of string to char str[2] and assign RED to it and then compile it and the again receive a output stating RE(Smiley face)

If someone can explain it to me I will be thankful . Posting the C code below

    int main()
{

 char s1[3]="RED";
 char s2[]="RED";
 puts(s1);
 puts(s2);
 printf("%s",s1);
 return 0;
}

Upvotes: 0

Views: 1812

Answers (2)

dhke
dhke

Reputation: 15398

char s1[3] = "RED";

Is a valid statement. It copies 3 characters from the constant string literal "RED" (which is 4 characters long) into the character array s1. There is no terminating '\0' in s1, because there is no room for it.

Note the copy, because s1 is mutable, while "RED" is not. This makes the statement different from e.g. const char *s1 = "RED";, where the string is not copied.

The result of both puts(s1) and printf("%s", s1) are undefined. There is no terminating '\0' in s1. Treating it as a string with one can lead to arbitrary behavior.

char s2[] = "RED";

Here, sizeof(s2) == 4, because "RED" has four characters, you need to count the trailing '\0' when calculating space.

Upvotes: 5

ma08
ma08

Reputation: 3744

The null character takes one exra character(byte). So you need to use an extra space in addition to the number of characters in the word you are initializing.

 char s1[4]="RED"; //3 for RED and 1 for the null character

On the other hand

char s2[3]="RED";

there is no space for null character. "RED" is in there but you would encounter I/O problems when printing it as there is no null character stored at the end. Your data is stored fine but it can't be recognized properly by the printf as there is no null character.

 char s2[]="RED";

This would work as memory of 4 (bytes) is automatically assigned which includes space for the terminating null character.

Upvotes: 4

Related Questions