简体   繁体   中英

what is the correct string terminator in c

As I know the string terminating character in c is '\\0'.

can we use '0' as the terminating character too? when I assign 0 to a specific index in a char array, and then use printf, it prints only upto that specific index.

hence, are both ways equivalent? is the null character equal to the literal 0?

The only value that can be used as a null terminator is the numerical value 0.

  • 0 is the numerical value 0.
  • '\\0' is also another way of representing the numerical value 0 in your code
  • '0' is not the numerical value 0 (it's the digit zero) and cannot be used as a terminator.

All strings literals implicitly contain the null terminator after their last visible character. In other cases, it may or may not be there automatically (depending on how the string was constructed), but you have to be sure that in every case the null terminator is there.

  • is the null character equal to the literal 0?

Yes.

The null character (also null terminator), abbreviated NUL, is a control character with the value zero.

  • can we use '0' as the terminating character too?

No. '0' is a character which has value 0x30. It is not null character and not equal to 0.

See this link: http://www.asciitable.com/

'\\0' is a convenient way of entering byte 0. It's called escaping. '0' is the character zero; very different. All strings in c are terminated with byte 0.

In C, strings are arrays of char's terminated with a '\\0'. When writing a char with single quotes, as in '\\0' you are reffering to the asci value of that char. Thus the expression: return '\\0' == 0; would return true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM