-3

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 
rioV8
  • 24,506
  • 3
  • 32
  • 49
Mrinaal
  • 7
  • 4
  • *there is also this weird space in the start*, you are printing a space in `printf`. Also, `l` and `m` needs to be of size `7` rather than `6` - one extra character for `NULL` (`'\0'`) terminator character. – kiner_shah Nov 03 '21 at 06:57
  • 1
    @kiner_shah thanks it worked, I just realized the size in strings will be one extra. – Mrinaal Nov 03 '21 at 07:03

2 Answers2

3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

"prac c", "stop c", "nice c" all occupy 7 bytes separately, as there's a terminating \0 for a string literal.

Wanghz
  • 305
  • 2
  • 12