Libft
42 Libft library documentation
Loading...
Searching...
No Matches
ft_itoa.c File Reference
#include <stdlib.h>
+ Include dependency graph for ft_itoa.c:

Go to the source code of this file.

Functions

char * ft_itoa (int n)
 Converts an integer to a newly allocated decimal string.
 
static size_t ft_num_len (int n)
 Computes the number of characters needed for an int string.
 

Function Documentation

◆ ft_itoa()

char * ft_itoa ( int  n)

Converts an integer to a newly allocated decimal string.

Parameters
nInteger value to convert.
Returns
Newly allocated string, or NULL on allocation failure.

Definition at line 23 of file ft_itoa.c.

24{
25 char *str;
26 size_t len;
27 unsigned int nb;
28
29 len = ft_num_len(n);
30 str = (char *)malloc(sizeof(char) * (len + 1));
31 if (!str)
32 return (NULL);
33 str[len] = '\0';
34 if (n < 0)
35 {
36 str[0] = '-';
37 nb = -n;
38 }
39 else
40 nb = n;
41 if (nb == 0)
42 str[0] = '0';
43 while (nb != 0)
44 {
45 str[--len] = (nb % 10) + '0';
46 nb /= 10;
47 }
48 return (str);
49}
static size_t ft_num_len(int n)
Computes the number of characters needed for an int string.
Definition ft_itoa.c:59

References ft_num_len().

+ Here is the call graph for this function:

◆ ft_num_len()

static size_t ft_num_len ( int  n)
static

Computes the number of characters needed for an int string.

Includes one extra character for a sign or for the value zero.

Parameters
nInteger value.
Returns
Required string length without the terminating null byte.

Definition at line 59 of file ft_itoa.c.

60{
61 size_t len;
62
63 len = 0;
64 if (n <= 0)
65 len++;
66 while (n != 0)
67 {
68 n /= 10;
69 len++;
70 }
71 return (len);
72}

Referenced by ft_itoa().

+ Here is the caller graph for this function: