NinjaYo. NinjaYo. - 11 months ago 51
C Question

who can please explain to me why this atoi command works and how

I wrote a very basic c code with atoi command, and execute it.

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);

The output will be as follow:

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 = ;

how this is possible? why atoi skip the amount of characters I wrote with + int?
I should be error, no?
and why the last printf also worked?

I read the documentation and there is nothing about this behavior:

int atoi (const char * str);
Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.

The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.

Answer Source

Consider for example statement

length = atoi("Content:    111" + 10);

This expression

"Content:    111" + 10

used as an argument in the function call contains the so-called pointer arithmetic.

The string literal "Content: 111" that has type char[16] is implicitly converted to pointer to its first character that is it gets type char *. Then integer value 10 is added to the pointer that yields the offset from the beginning of the string literal.

Thus expression

"Content:    111" + 10

points to the marked position in the string literal.

You can imaging the function call the following way

char *tmp = "Content:    111";
tmp = tmp + 10;
puts( tmp ); // just for testing
length = atoi( tmp );

The function skips leading white space characters until a digit or a sign will be encountered and extracts number 111. That is all.:)