The following code does not compile:

#include <stdio.h> #include <stdlib.h> int main(int argc, char const *argv[]) { char str[] = "123456789"; printf("str: %s\n", str); int two = atoi(str[1]); printf("two: %i\n", two); } 

The compiler writes:

  warning: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Wint-conversion] int two = atoi(str[1]); 

If you put & before atoi , it is compiled, but it translates the entire string, starting with str[1] into a number. How can I convert to the number of only one character from the string - str[1] ?

  • 2
    With the help of atoi only this way: create a new string of length 1, copy the desired character there and transfer to atoi . The atoi function takes a STRING. Or easier. 1 character is 1 digit, then str [1] - '0' and will be this digit. - Alexey Sarovsky
  • @ AlekseySarovsky, more thanks! Write your comment as an answer so that I can accept it. - eanmos

2 answers 2

With the help of atoi only this way: create a new string of length 1, copy the desired character there and transfer to atoi. The atoi function takes a STRING. Or easier. 1 character is 1 digit, then str[1]-'0' and will be this digit

    So look at the prototype:

     int atoi(const char *nptr); 

    The function accepts a pointer to the string ( char * ), and you give it a character ( char ). Therefore it is not compiled.

    And to translate into the number of one character (provided that it is a decimal digit) is very simple:

     int two = str[1] - '0';