开发者

length of string containing \0

 char p[]="abc\012\0x34"; 
 printf("%d\n",strlen(p));

I 开发者_开发技巧am getting output 4. Shouldn't it be 3 ??? Although for following i am getting 3.

 char p[]="abc\0"; 
 printf("%d\n",strlen(p));


Your string does contain four characters before the \0, i.e. abc and \012.

The latter is a valid octal escape sequence, which is 10 in decimal, i.e an ASCII linefeed character.

\0x34 on the other hand isn't valid octal - only the \0 part is valid hence that's the real end of your NUL terminated string.


\012 is an octal escaped character, not a NUL followed by 1 and 2. x terminates the second octal character so it is genuinely a NUL. (\x34 would be the correct form for a hexadecimal escaped character.)

The representation of a NUL character as \0 is just a special case of an octal escape sequence. In general a \ can be followed by one, two or three octal digits to form a valid octal escape sequence in a character or string literal.


Your string has length 4:

You code is equivalent to: char p[]={'a','b'.'c'.'\012','\0','x','3','4','\0'};

\012 - character with code 12 in octal numeral system (= 10 in decimal = '\n')


\012 is a single character. It's stopping on the \0 after that (and "x34" is three more characters, not counting the NUL terminator).


\012 is an octal value("\n").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜