Converting integers to strings in C
I found a simple way to convert integers into strings the safe and easy way. I used the power of the C Standard Library to help me out (calloc, malloc, memcpy, sprintf).
Here is the source:
/********************************************************************
* Name: inttostr.c
* Author: Rashaud Teague
* Date: 02/13/2010
* License: GNU LGPL <http://www.gnu.org/licenses/>
* Description: <description>
********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * itoa(int i) {
/* declare/initialize a place holder text */
char *text = (char *) calloc(256, sizeof(char));
if (text == NULL) return NULL;
/* declare a return text */
void *rtext;
/* use sprintf to format the integer into a string */
sprintf(text, "%d", i);
/*
* allocate the correct size for the return text (rtext)
* then copy the block of memory from text to rtext
* and free text
*/
if ((rtext = malloc(strlen(text))) == NULL) return NULL;
memcpy(rtext, (void *)text, strlen(text));
free(text);
return (char *)rtext;
}
int main(void) {
char *str = itoa(2010);
printf("My string integer: %s\n", str);
return 0;
}
* Name: inttostr.c
* Author: Rashaud Teague
* Date: 02/13/2010
* License: GNU LGPL <http://www.gnu.org/licenses/>
* Description: <description>
********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * itoa(int i) {
/* declare/initialize a place holder text */
char *text = (char *) calloc(256, sizeof(char));
if (text == NULL) return NULL;
/* declare a return text */
void *rtext;
/* use sprintf to format the integer into a string */
sprintf(text, "%d", i);
/*
* allocate the correct size for the return text (rtext)
* then copy the block of memory from text to rtext
* and free text
*/
if ((rtext = malloc(strlen(text))) == NULL) return NULL;
memcpy(rtext, (void *)text, strlen(text));
free(text);
return (char *)rtext;
}
int main(void) {
char *str = itoa(2010);
printf("My string integer: %s\n", str);
return 0;
}
Have fun,
Rashaud