You say you want to write a function that converts an integer into a string, but you refer to
atoi (which converts a string to an integer). Which way do you want the conversion to go?
2's complement is by far the most common encoding technique, but others are permitted by the C Standard. If we assume that your function works properly for positive integers, then the following snippet handles almost all negative numbers properly. (It looks like you are sort of trying to do something like this.)
- if (value < 0)
-
return intToStr(-value);
-
else
-
return intToStr(value);
However, it fails for negative numbers where -
value cannot be represented as a positive number (eg, |
INT_MIN| >
INT_MAX, as is typically the case for 2's complement). This is a corner case that can be hard to handle.
However, there are problems with
intToStr:
- The function is defined to return a char, but it actually returns a pointer to char.
- The function returns a pointer to automatic variable r for use outside the scope of r.
- It tests a[0] as if a were a char pointer, but a is actually an int.
- sign is undefined if a[0] is not '-'.
- The function only converts a single decimal digit of the input.
- In the final loop that copies s to r, j is undefined.
- Converting integer digit to string digit via n | '0' will work for ASCII string encoding but could fail for other string encodings. The traditional way to do this is via n + '0'.
- There are more problems, but these are a good start.