Search code examples
cstringvariablesprintf

Why are my strings getting concatenated as I initialize them?


I'm trying to practice declaring Strings but I'm not getting correct output.

#include <stdio.h>                   //Im using vscode and gcc
int main()
{
    char k[]= "prac c";
    char l[6]= "stop c";            //first initializing as size 6
    char m[6]= "nice c";

    printf("%s \n%s \n%s",k,l,m);
    return 0;
 }

output: prac c
        stop cprac c
        nice cstop cprac c    

But when I change the size from 6 to 7 this does not happen.

#include <stdio.h>
int main()
{
    char k[]= "prac c";
    char l[7]= "stop c";     //changing size to 7
    char m[7]= "nice c";     //changing size to 7

    printf("%s \n%s \n%s",k,l,m);
return 0;
}

output: prac c
        stop c
        nice c 

Solution

  • The string "stop c" is really seven characters long, including the ending null-terminator. This goes for all your strings.

    If there's no space in your arrays for the terminator then it won't be added, and the arrays are no longer what is commonly called strings.

    Using such arrays as string will lead the code to go out of bounds of the arrays and give you undefined behavior.