I am trying to read data from the ADC and display it on a HD44870 compatible LCD with an ATmega32. As the data from the ADC is a 10-bit unsigned integer, the LCD expects a string, some conversion is necessary. Below is the function i wrote to accomplish this conversion.

char *int_to_str(uint16_t num, uint8_t len){
    uint8_t i;
    char *str;
    for(i=(len-1); i>=0; i--){
        str[i] = '0' + num % 10;
    return str;

However, the above function does not work. I just get a blank display where the numbers should be displayed. I am currently using itoa() and it works. However, i would prefer to write my own since size of the resulting executable is critical. Thank you.

  • \$\begingroup\$ Check up on sprintf(). You are confusing integer and string manipulation. \$\endgroup\$
    – jippie
    Jan 6, 2013 at 17:01
  • \$\begingroup\$ sprintf probably uses itoa internally,and is likely to be larger. \$\endgroup\$ Jan 6, 2013 at 18:16
  • \$\begingroup\$ Why do you think writing your own implementation of itoa() will be smaller? \$\endgroup\$
    – Phil Frost
    Jan 7, 2013 at 3:39

2 Answers 2


There is no reason why sprintf wouldn't work. This basically prints a string to a buffer instead of standard output.

As an example

char string[256];
int value = 5;
memset(string,0,sizeof(string[0])*256); // Clear all to 0 so string properly represented
sprintf(string,"Value: %d",value);

string will now contain the string "Value: 5"


Your way of handling strings is incorrect. You've just made a stack variable pointer to a string that is not initialized and does not point to a string with a valid length.

Declare str as str[len] and try that way.

  • 1
    \$\begingroup\$ Your first paragraph is correct, and probably adresses correctly the original problem. But "Declare str as str[len] and try that way" is a big no-go when you return a pointer to that (local!) variable later, as the OP intends to do, see return str;. \$\endgroup\$
    – JimmyB
    Sep 10, 2016 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.