C语言中字符串的八进制表示形式 [英] Octal representation inside a string in C

查看:1733
本文介绍了C语言中字符串的八进制表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定程序中:

int main() {
  char *p = "\0777";
  printf("%d %d %d\n",p[0],p[1],p[2]);
  printf("--%c-- --%c-- --%c--\n",p[0],p[1],p[2]);
  return 0;  
}

它将输出显示为:

63 55 0
-?---7-- ----

63 55 0
--?-- --7-- ----

我可以理解,它会将 \ 0 (\ 077)之后的前两个字符从八进制转换为十进制,但是谁能解释我为什么2个字符,为什么不是1或3或任何其他?

I can understand that it is converting the first two characters after \0 (\077) from octal to decimal but can any one explain me why 2 characters, why not 1 or 3 or any other ?

请解释其背后的逻辑.

推荐答案

char *p = "\07777";

这里是分配给char指针的字符串文字.

Here a string literal assigned to a pointer to a char.

"\07777"

在此字符串中使用了文字八进制转义序列,因此前三位数字代表一个八进制数字.因为八进制转义序列的规则是---

In this string literal octal escape sequence is used so first three digits represents a octal number.because rules for octal escape sequence is---

您只能在八进制转义序列中使用数字0到7. 八进制转义序列不能超过三位数,并且以不为八进制数字的第一个字符结尾.尽管不需要全部使用三位数,但必须至少使用一个数字.例如,八进制表示形式为\ 10(对于ASCII退格字符)和\ 101(对于字母A),如ASCII图表中所示.

You can use only the digits 0 through 7 in an octal escape sequence. Octal escape sequences can never be longer than three digits and are terminated by the first character that is not an octal digit. Although you do not need to use all three digits, you must use at least one. For example, the octal representation is \10 for the ASCII backspace character and \101 for the letter A, as given in an ASCII chart.

将您的字符串文字存储在

SO your string literal stored in memory like

第一个字节作为八进制数字077,除了十进制的63和'?'之外,什么都没有.字符

1st byte as a octal number 077 which is nothing but 63 in decimal and '?' in character

第二和第三字节分别为字符"7"和"7"

2nd and 3rd byte as a characters '7' and '7' respectively

最后是一个终止字符'\ 0'.

and a terminating character '\0' in last.

所以您的答案符合预期的字符串文字的第1、2、3d字节.

so your answer are as expected 1st,2nd,3d byte of the string literal.

有关更多说明,您可以访问此网站

for more explanation you can visit this web site

http://msdn.microsoft.com/en-us/library/edsza5ck.aspx

这篇关于C语言中字符串的八进制表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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