C将char数组转换成int表现得很奇怪

del*_*lta 5 c arrays string integer

我有一个更长的char数组,我正在变成整数,但我无法弄清楚为什么它在某些地方表现得很奇怪.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () 
{
    char x[60] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
    printf("%lu\n\n", strlen(x));

    for ( int i = 0; i < strlen(x); i+=3 ) {
        char num[2];
        num[0] = (char)x[i];
        num[1] = (char)x[i+1];
        printf("%d, ", atoi(num));
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 500, 773, 916, 89, 
Run Code Online (Sandbox Code Playgroud)

一切都很好,直到..... 500,773,916,89 ......发生了什么?

LPs*_*LPs 12

正如你所看到的,atoi想要一个C-String:一个空终止的字符数组.

所以这

    char num[2];
    num[0] = (char)x[i];
    num[1] = (char)x[i+1];
Run Code Online (Sandbox Code Playgroud)

不得不

    char num[3] = {0};
    num[0] = (char)x[i];
    num[1] = (char)x[i+1];        
    num[2] = '\0'; // this could be avoided in your specific case
Run Code Online (Sandbox Code Playgroud)

  • 不,这是未定义的行为,并解释实际发生的事情需要深入了解实现细节(编译器,处理器,callstack,OS) (2认同)