Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 614
DesirePRG Avatar asked May 18 '13 18:05

DesirePRG


People also ask

What is the string termination character in C?

Strings are actually one-dimensional array of characters terminated by a null character '\0'.

What is a string terminator?

All character strings are terminated with a null character. The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0.

What is the correct declaration of a string in C?

The general syntax of declaring a string in C is as follows: char variable[array_size]; Thus, the classic declaration can be made as follows: char str[5]; char str2[50]; It is vital to note that we should always account for an extra space used by the null character(\0).

What is the purpose of '\ 0 character in C?

“\0” is the null termination character. It is used to mark the end of a string. Without it, the computer has no way to know how long a group of characters (string) goes. In C/C++ it looks for the Null Character to find the end of a string.


1 Answers

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.

like image 95
Theodoros Chatzigiannakis Avatar answered Nov 15 '22 08:11

Theodoros Chatzigiannakis