3

What is the difference between using atoi(x) vs (int) x, given x = 10?

I tested and found that:

int main(void) { string x = "11"; printf("%i\n", (int) x); }

returned 440546, whereas:

int main(void) { string x = "11"; printf("%i\n", atoi(x)); }

returned 11.

So what is (int) doing? I thought that in a lecture David said that's how you cast to a different type.

8

Type casting using (int) would work predictably on a single char, although it would probably not give you the result you are expecting anyway. It does not give anything meaningful on a string.

A string is just an array of chars where the variable name is a pointer (or memory address) to the first element in that array. In your first example, you are trying to cast a pointer to an integer, which is why you don't get the result you expected.

Try running the following code instead:

int main(void) {
    string x = "11";
    printf("%i\n", (int) *x);
}

This would give a predictable result as it casts the data that x is pointing to to an int, but it would still not give you 11. It would cast only the first element of the array x (or x[0]) to an integer, which would return 49 as the number 1 is stored as a char with ASCII value 49. Casting a char to an int just changes the way the information is displayed.

This is why you should use atoi()!

| improve this answer | |
  • Thanks for giving me useful pointers (!!!) Your answer was very helpful. – alex1x Feb 9 '17 at 9:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .