andrehigher andrehigher - 1 month ago 24
C Question

atoi in C returning -1

I'm trying to read some input in a C program but for some reason

atoi
is returning
-1
.

Am I doing something wrong?

Follow my input and my code:

Input:

20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690


Algorithm:

loop here ( i++, j-- ) {

printf( "%c %d\n", A[ i ][ j ], atoi( &A[ i ][ j ] ) );

}


Output:

...
2 -1
5 -1


Look that
2
and
5
is the first numbers of the input. So printing as
%c
is working as expected but the
atoi
function is not working properly.

AnT AnT
Answer

Firstly, it appears that you are actually trying to convert a single digit character from '0'..'9' range to its corresponding integer representation from 0..9 range. atoi is not supposed to do that. atoi expects a string as its input and single character is not a string. There are no functions in standard library for converting a single character, albeit you can easily do it manually by subtracting '0' from the character value.

Secondly, atoi produces undefined behavior on overflow, which is what happens in your code, considering the size of the input. Don't use atoi. The function is essentially useless. If you want to convert a string, use functions from strto... group.