Nin*_*Yo. 0 c atoi string-literals pointer-arithmetic
我用atoi命令编写了一个非常基本的c代码,然后执行它.
void
main
(void)
{
int length;
length = atoi("Content: 111");
printf("atoi(\"Content: 111\") = %d\n",length);
length = atoi("Content: 111" + 10);
printf("atoi(\"Content: 111\" + 10) = %d\n",length);
length = atoi("Content: 1" + 6);
printf("atoi(\"Content: 1\" + 6) = %d\n",length);
length = atoi("Content: 111" + 12);
printf("atoi(\"Content: 111\" + 12) = %d\n",length);
length = atoi("Content-aaaaaa: 111" + 20);
printf("atoi(\"Content-aaaaaa: 111\" + 20) = %d\n",length);
printf("\"aaa\"+7 = %s","aaa"+7);
}
Run Code Online (Sandbox Code Playgroud)
输出如下:
atoi("Content: 111") = 0
atoi("Content: 111" + 10) = 111
atoi("Content: 1" + 6) = 0
atoi("Content: 111" + 12) = 0
atoi("Content-aaaaaa: 111" + 20) = 111
"aaa"+7 = ;
Run Code Online (Sandbox Code Playgroud)
怎么可能?为什么atoi跳过我用+ int写的字符数量?我应该是错误,不是吗?为什么最后一个printf也有效?
我阅读了文档,但没有任何关于此行为:
int atoi(const char*str); 将字符串转换为整数解析C字符串str将其内容解释为整数,该值作为int类型的值返回.
该函数首先丢弃尽可能多的空白字符(如在isspace中),直到找到第一个非空白字符.然后,从该字符开始,采用可选的初始加号或减号,后跟尽可能多的基数为10的数字,并将它们解释为数值.
字符串可以包含在形成整数之后的其他字符,这些字符将被忽略并且对此函数的行为没有影响.
如果str中的第一个非空白字符序列不是有效的整数,或者由于str是空的或者只包含空格字符而不存在这样的序列,则不执行转换并返回零.
atoi 解析整数,但也接受前导空格字符.
其余的是简单的指针算术.
"Content: 111" + 10你会传递" 111"给atoi并且它有效."Content: 1" + 6你传递"t: 1到atoi并返回0."aaa"+7:不要这样做:未定义的行为.