[c] Converting int to string in C

I am using the itoa() function to convert an int into string, but it is giving an error:

undefined reference to `itoa'
collect2: ld returned 1 exit status

What is the reason? Is there some other way to perform this conversion?

This question is related to c

The answer is


Use snprintf - it is standard an available in every compilator. Query it for the size needed by calling it with NULL, 0 parameters. Allocate one character more for null at the end.

int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);

Like Edwin suggested, use snprintf:

#include <stdio.h>
int main(int argc, const char *argv[])
{
    int n = 1234;
    char buf[10];
    snprintf(buf, 10, "%d", n);
    printf("%s\n", buf);
    return 0;
}

see this example

#include <stdlib.h> // for itoa() call
#include <stdio.h>  

int main() {
    int num = 145;
    char buf[5];

    // convert 123 to string [buf]
    itoa(num, buf, 10);

    // print our string
    printf("%s\n", buf);

    return 0;
}

see this link having other examples.


Similar implementation to Ahmad Sirojuddin but slightly different semantics. From a security perspective, any time a function writes into a string buffer, the function should really "know" the size of the buffer and refuse to write past the end of it. I would guess its a part of the reason you can't find itoa anymore.

Also, the following implementation avoids performing the module/devide operation twice.

char *u32todec( uint32_t    value,
                char        *buf,
                int         size)
{
    if(size > 1){
        int i=size-1, offset, bytes;
        buf[i--]='\0';
        do{
            buf[i--]=(value % 10)+'0';
            value = value/10;
        }while((value > 0) && (i>=0));
        offset=i+1;
        if(offset > 0){
            bytes=size-i-1;
            for(i=0;i<bytes;i++)
                buf[i]=buf[i+offset];
        }
        return buf;
    }else
        return NULL;
}

The following code both tests the above code and demonstrates its correctness:

int main(void)
{
    uint64_t acc;
    uint32_t inc;
    char buf[16];
    size_t bufsize;
    for(acc=0, inc=7; acc<0x100000000; acc+=inc){
        printf("%u: ", (uint32_t)acc);
        for(bufsize=17; bufsize>0; bufsize/=2){
            if(NULL != u32todec((uint32_t)acc, buf, bufsize))
                printf("%s ", buf);
        }
        printf("\n");
        if(acc/inc > 9)
            inc*=7;
    }
    return 0;
}

Better use sprintf(),

char stringNum[20];
int num=100;
sprintf(stringNum,"%d",num);

Before I continue, I must warn you that itoa is NOT an ANSI function — it's not a standard C function. You should use sprintf to convert an int into a string.

itoa takes three arguments.

  • The first one is the integer to be converted.
  • The second is a pointer to an array of characters - this is where the string is going to be stored. The program may crash if you pass in a char * variable, so you should pass in a normal sized char array and it will work fine.
  • The last one is NOT the size of the array, but it's the BASE of your number - base 10 is the one you're most likely to use.

The function returns a pointer to its second argument — where it has stored the converted string.

itoa is a very useful function, which is supported by some compilers - it's a shame it isn't support by all, unlike atoi.

If you still want to use itoa, here is how should you use it. Otherwise, you have another option using sprintf (as long as you want base 8, 10 or 16 output):

char str[5];
printf("15 in binary is %s\n",  itoa(15, str, 2));

itoa() function is not defined in ANSI-C, so not implemented by default for some platforms (Reference Link).

s(n)printf() functions are easiest replacement of itoa(). However itoa (integer to ascii) function can be used as a better overall solution of integer to ascii conversion problem.

itoa() is also better than s(n)printf() as performance depending on the implementation. A reduced itoa (support only 10 radix) implementation as an example: Reference Link

Another complete itoa() implementation is below (Reference Link):

#include <stdbool.h> 
#include <string.h>

// A utility function to reverse a string 
char *reverse(char *str)
{
  char *p1, *p2;

  if (! str || ! *str)
        return str;
  for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
  {
        *p1 ^= *p2;
        *p2 ^= *p1;
        *p1 ^= *p2;
  }
  return str;
}
// Implementation of itoa() 
char* itoa(int num, char* str, int base) 
{ 
    int i = 0; 
    bool isNegative = false; 
  
    /* Handle 0 explicitely, otherwise empty string is printed for 0 */
    if (num == 0) 
    { 
        str[i++] = '0'; 
        str[i] = '\0'; 
        return str; 
    } 
  
    // In standard itoa(), negative numbers are handled only with  
    // base 10. Otherwise numbers are considered unsigned. 
    if (num < 0 && base == 10) 
    { 
        isNegative = true; 
        num = -num; 
    } 
  
    // Process individual digits 
    while (num != 0) 
    { 
        int rem = num % base; 
        str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0'; 
        num = num/base; 
    } 
  
    // If number is negative, append '-' 
    if (isNegative) 
        str[i++] = '-'; 
  
    str[i] = '\0'; // Append string terminator 
  
    // Reverse the string 
    reverse(str); 
  
    return str; 
} 

Another complete itoa() implementatiton: Reference Link

An itoa() usage example below (Reference Link):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
    int a=54325;
    char buffer[20];
    itoa(a,buffer,2);   // here 2 means binary
    printf("Binary value = %s\n", buffer);
 
    itoa(a,buffer,10);   // here 10 means decimal
    printf("Decimal value = %s\n", buffer);
 
    itoa(a,buffer,16);   // here 16 means Hexadecimal
    printf("Hexadecimal value = %s\n", buffer);
    return 0;
}

char string[something];
sprintf(string, "%d", 42);

You can make your own itoa, with this function:

void my_utoa(int dataIn, char* bffr, int radix){
int temp_dataIn;
temp_dataIn = dataIn;
int stringLen=1;

while ((int)temp_dataIn/radix != 0){
    temp_dataIn = (int)temp_dataIn/radix;
    stringLen++;
}
//printf("stringLen = %d\n", stringLen);
temp_dataIn = dataIn;
do{
    *(bffr+stringLen-1) = (temp_dataIn%radix)+'0';
    temp_dataIn = (int) temp_dataIn / radix;
}while(stringLen--);}

and this is example:

char buffer[33];
int main(){
  my_utoa(54321, buffer, 10);
  printf(buffer);
  printf("\n");

  my_utoa(13579, buffer, 10);
  printf(buffer);
  printf("\n");
}

Usually snprintf() is the way to go:

char str[16]; // could be less but i'm too lazy to look for the actual the max length of an integer
snprintf(str, sizeof(str), "%d", your_integer);

void itos(int value, char* str, size_t size) {
    snprintf(str, size, "%d", value);
}

..works with call by reference. Use it like this e.g.:

int someIntToParse;
char resultingString[length(someIntToParse)];

itos(someIntToParse, resultingString, length(someIntToParse));

now resultingString will hold your C-'string'.


If you really want to use itoa, you need to include the standard library header.

#include <stdlib.h>

I also believe that if you're on Windows (using MSVC), then itoa is actually _itoa.

See http://msdn.microsoft.com/en-us/library/yakksftt(v=VS.100).aspx

Then again, since you're getting a message from collect2, you're likely running GCC on *nix.