Search code examples
c++carraysatoiitoa

Converting a [char] variable to [int] then back to [char]


I am using Visual C 6

I am trying to convert a character array (single-quotation) into an integer, then incrementing the value by 1, then storing the result back into a different character array..

But I keep getting an unexpected value when converting back to character..

Here is my code

   char char_array[4];
   char_array[0] = '1';
   char_array[1] = '2';
   char_array[2] = '3';
   char_array[3] = '\0';  //Terminating character

   int my_number = atoi(char_array);  
   printf("my_number = %d" , my_number);   // output is 123

   my_number++;    // works and my_number is incremented =124
   printf("now: my_number = %d" , my_number);   // output is 124


   char result[4];  //declared to store the result

   result = itoa(my_number);  // Output is unexpected.

   printf("%c", result[0]);    // Output is  2  instead of 1
   printf("%c", result[1]);    // Output is  2
   printf("%c", result[2]);    // Output as  3   instead of 4

It seems that the function itoa() somehow knows the original value 123 and in some weird way knows that I have incremented that value.. but the addition is done to the wrong digit. Instead of adding 1 to the least significant digit, the addition is done to the most significant digit.


Solution

  • I find it really difficult to believe that your compiler is letting this code through:

    char result[4];  //declared to store the result
    result = itoa(my_number);  // Output is unexpected.
    

    For one reason, you're attempting to reseat an array. Which shouldn't be allowed. For another, itoa() normally takes three arguments. It's prototype should look like:

    char *itoa(int value, char * str, int base);
    

    So you should be calling it as:

    char result[4];
    itoa(my_number, result, 10);
    

    Or, if you'd like to use portable functions that don't have possible buffer overflows:

    char result[4];
    snprintf(result, 4, "%d", my_number);