strlen的 - 的字符串的长度,有时增加1 [英] strlen - the length of the string is sometimes increased by 1

查看:140
本文介绍了strlen的 - 的字符串的长度,有时增加1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一些C谜的问题。在大多数情况下,我能够找到正确的答案,但有一个我遇到的问题。我知道,通过使用编译器正确的答案,但我不知道原因。

I'm doing some C puzzle questions. In most cases, I am able to find the right answer, but with that one I am having problems. I know the right answer by using the compiler, but I don't know the reason.

有一个看code:

char c[] = "abc\012\0x34";

会是什么 strlen的(C)回报,使用标准C编译器?

What would strlen(c) return, using a Standard C compiler?

我的编译器返回时4我期望的是3

My compiler returns 4 when what I expected was 3.

我以为是的strlen()将搜索 NULL 字符中第一次出现,但不知何故结果比我预期的一个。

What I thought is strlen() would search for the first occurrence of the NULL character but somehow the result is one more than I expected.

任何想法,为什么?

推荐答案

让我们写

char c[] = "abc\012\0x34";

单字符:

char c[] = { 'a', 'b', 'c', '\012', '\0', 'x', '3', '4', '\0' };

第一个 \\ 0 你看到的是一个八进制转义序列的开始 \\ 012延伸过以下八进制数字。

The first \0 you see is the start of an octal escape sequence \012 that extends over the following octal digits.

八进制转义序列标准(N1570草案)第6.4.4.4规定:

Octal escape sequences are specified in section 6.4.4.4 of the standard (N1570 draft):

八进制转义序列:的结果
      \\ 八进制数字的结果
      \\ 八八进制数字的结果
      \\ 八八进制八进制数字

octal-escape-sequence:
\ octal-digit
\ octal-digit octal-digit
\ octal-digit octal-digit octal-digit

他们由一个反斜杠后面跟着一个,两个或三个八进制数字的。该节第7段,八进制和十六进制转义序列的程度给出:

they consist of a backslash followed by one, two, or three octal digits. In paragraph 7 of that section, the extent of octal and hexadecimal escape sequences is given:

7的每个八进制或十六进制转义序列的最长序列,可以
  构成的转义序列。

7 Each octal or hexadecimal escape sequence is the longest sequence of characters that can constitute the escape sequence.

请注意,虽然一个八进制转义序列的长度被限制为最多三个八进制数字(因而\\ 123456由五个字符, {'\\ 123','4','5','6','\\ 0'} ),十六进制转义序列具有无限长度

Note that while the length of an octal escape sequence is limited to at most three octal digits (thus "\123456" consists of five characters, { '\123', '4', '5', '6', '\0' }), hexadecimal escape sequences have unlimited length

十六进制转义序列:的结果
       \\ X 十六进制数字的结果
      的十六进制转义序列十六进制数字

和由此\\ x123456789abcdef仅由两个字符(的{'\\ x123456789abcdef','\\ 0'} )。

and thus "\x123456789abcdef" consists of only two characters ({ '\x123456789abcdef', '\0' }).

这篇关于strlen的 - 的字符串的长度,有时增加1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆