ft_itoa — Integer to String
Allowed functions: malloc
Write a function that takes an int and converts it to a null-terminated string. The function returns the result in a char array that you must allocate.
char *ft_itoa(int nbr);
Solution
Download ft_itoa.c#include <stdlib.h>
int numlen(int n) {
int len = 0;
if (n <= 0)
len = 1;
while (n != 0) {
n = n / 10;
len++;
}
return len;
}
char *ft_itoa(int nbr) {
long n = nbr;
int length = numlen(nbr);
char *str = malloc(sizeof(char) * (length + 1));
if (!str) {
return NULL;
}
if (n < 0) {
n = -n;
str[0] = '-';
}
if (n == 0)
str[0] = '0';
while (n > 0) {
length--;
str[length] = n % 10 + '0';
n = n / 10;
}
str[length] = '\0';
return str;
}
How It Works
Goal: Convert an integer to a dynamically allocated null-terminated string.
Approach: Count the number of digits, allocate a string of that size, then fill it from the end by extracting digits with modulo.
Step by step:
numlencounts digits — it starts at 1 for zero or negative numbers (to account for'0'or'-'), then divides by 10 until the number is 0.- Allocate a char array of
length + 1(for the null terminator). - If the number is negative, store
'-'at index 0 and negate the value (usinglongto safely handleINT_MIN). - Fill digits from the end:
str[--length] = n % 10 + '0'extracts the last digit, thenn /= 10removes it.
Key concept: Digit extraction using modulo and division, handling negative numbers and zero as edge cases.