sscanf 从八进制转换:它怎么知道的?

sscanf converting from octal: How does it know?

我有将字符串转换为 int 的代码

unsigned int formatInt(char *ptr) {
    int res;
    if (sscanf(ptr, "%i", &res) == -1) exit(-1);
    return res;
}

我给它一个 char * 指向“00000000041”的第一个字符。

转换为 int returns me 33(隐式八进制到十进制转换)

“00000000041”实际上是一个字符串(char[12]),但它是八进制的文件大小。

编译器怎么知道它是八进制的? 00000000041 完全可以是小数 (41)

将字符串识别为八进制是 %i 格式说明符 scanf 的功能。来自手册页:

   i      Matches an optionally signed integer; the next pointer must be a
          pointer to int.  The integer is read in base  16  if  it  begins
          with  0x  or  0X,  in base 8 if it begins with 0, and in base 10
          otherwise.  Only characters that  correspond  to  the  base  are
          used. 

因为字符串以 0 开头并且使用了 %i,所以它被解释为八进制字符串。