top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

How atoi() works - char to int?

+3 votes

In K&R I found a piece of code which showed how atoi() works. It said like s[i] - '0' will give a numeric value of the character.

Can someone please explain it to me. I tried to search around but they only explain it with integers and not with characters. Say you are given s[i] = 'C'.

posted Oct 22, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

I would suggest you to go through the manual page of atoi() "man atoi".

Here is my answer:
As per manual page of atoi() it convert a sting to an integer.
It will only convert a string which has an integer value i.e
1> char str1[10] = "123456789"; //string which contains integer value
2> char str2[10] = "abcD"; //string with non integer values.
So atoi(str1); // will give you a integer value 123456789 but
atoi(str2); // it will give any value, because atoi() won’t detect error.

So basically atoi() is used to convert a string which has valid integer value. It won't work same as on other values.

Hope you understand now. :)

answer Oct 23, 2014 by Arshad Khan
Similar Questions
+1 vote

What type of conversion is not accepted in C and why?
a) char to int
b) float to char pointer
c) int to char
d) double to char

+4 votes

I am wanting to extract variable names and their size (int, char and etc.) from a c file.
Is there any way to extract that type of information?

+4 votes

What will be the output of this code?

 void main(){
       int i=320;
       char *ptr=(char *)&i;
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.