ft_itoa
Subject
FT_ITOA (simplified)
NAME
ft_itoa -- convert an int to a string
SYNOPSIS
char *ft_itoa(int n);
DESCRIPTION
Allocate (with malloc(3)) and returns a string representing n.
Negative numbers must be handled.
PARAMETERS
n: int to convert
RETURN VALUES
ft_itoa() returns the string representing n; NULL if the memory allocation failed.
AUTHORIZED EXTERNAL FUNCTIONS
malloc(3)
Understandable explanation
The ft_itoa
function does the opposite work of ft_atoi
, converting a number to a string.
Hints
Since we need to allocate some memory for the new string created from the int value we received, we have to count how much memory we have to allocate.
We have a function that count the length of a string, so for this one we'll build one counting the number of characters representing a number.
Remember that -
is also a character for negative numbers, so don't forget to count it when counting.
Once we know the number of characters representing the value we received, we need to allocate enough memory for it plus the NUL-terminating character.
Once that is done, we can start converting our number to string, the easiest way to do it is to go from right to left, since we know how much character the string will be, and we can use the modulo operator to get the last character of the number. And then we can simply divide the number by ten to remove the last character from it.
Remember this :
int a = 124;
int b = 10;
int c = a / b;
printf("%d\n", c); => 12
Since both values are integers, the division will effectuated as an integer division, meaning that there's no remainder nor floating point values in the result, that's why we get 12 by dividing 124 by 10.
Commented solution
Last updated
Was this helpful?