Home > Back-end >  Why str[0] = 0 clears all string in array?
Why str[0] = 0 clears all string in array?

Time:12-02

the given code is:

int main()
{
    char *str = "hello world";
    str[0] = 0;
    printf("%s\n", str); //prints nothing
}

I know that I can't edit the part of the string like 'str[5] = 'w;',

so I thought that line 4 'str[i] = 0;' would work like this.

But it seems to clear the string and thus prints nothing.

Can someone please explain why line 4 works like that?

CodePudding user response:

0 or '\0' is a null character.

In the C language, a string is a null-terminated array of chars.

So, if you put 0 at the very first element of the char array, it will represent an empty string (having length zero) when interpreted as a null-terminated string, such as by the %s specifier of printf().

But, your code is invalid, because you can't modify a string literal. It has to be more like this instead:

int main()
{
    char str[] = "hello world";
    str[0] = 0;
    printf("%s\n", str); //prints nothing
}
  •  Tags:  
  • c
  • Related