How does a String terminate in C?

117 Views Asked by At

I know the string in c will be terminated by a character \0.

However, if I do char a[5]="abcd\n" , where would \0 be?

Or do I need to reserve at least one position for \0, whenever I try to use char[] to store a string?

Thank you for any help!

1

There are 1 best solutions below

0
DanielHsH On BEST ANSWER

You should do:

char a[]="abcd\n";

without specifying the size to let compiler figure out the buffer size. The actual buffer will have size of 6 to accommodate your 5 bytes + 1 byte for terminating zero. When you type "something" without assignment, compilaer puts that string in a dedicated place in the program with at least 1 zero byte after the last character.

Writing char a[5]="abcd\n" is a bad practice because it will cause functions like strcpy() to act in undefined manner as your variable 'a' is not a c string, but just a buffer of characters, which by chance seem to be all printable/visible + terminating \n