0
char xs[7] = {'0','0','0','1','0','1','0'};
long ss = strtol(xs, NULL, 2);

在第二行 ss 之后是 2147483647,有什么想法吗?以下代码在循环中(在外面可以正常工作)

4

1 回答 1

1

strtol expects a NUL terminated string. Your array declaration creates a 7 character array and populates all 7 positions with non-NUL data. Thus, strtol actually continues to look up the stack (or through memory) until it finds a terminating character.

You have a number of options for declaring a char array and initializing it correctly. If it is a read-only array, I prefer:

char xs[] = "0001010";

which will create an array large enough to hold the string literal (including its terminating NUL).

Other options are shown in the comments above

char xs[7+1] = "0001010\0";
char xs[7+1] = {'0','0','0','1','0','1','0',0};
char xs[ ] = {'0','0','0','1','0','1','0',0};

The advantage of either my approach, or the final one above, is that you don't need to count the characters, and the compiler will adjust if you change the string.

In the first example above, \0 is the escape sequence representing the ASCII NUL character. It is preferable to a plain 0 because (a) it has the correct type (char) for inclusion in a string literal, and (b) most syntax-aware editors will highlight it, as a NUL in the middle of a literal can have surprising results. For example

   strlen("abc\0def") == 3
于 2014-12-17T20:17:08.670 回答