citoa

inteager to argument in C; gdb shows no errors, function is not giving output


** Hello :)

So I have this task to write a program that will convert int to arg using malloc and well it all works fine, gdb shows no errors, but it is not printing any output in this form. If i delete itoa_buffer[i] = '\0'; than sometimes it shows output sometimes not. I do not know what is wrong here, seems fine.

I do not know where to ask for help as I like to follow my logic and find errors here instead of copying solutions from the internet. I willl appreciate some tips, its probably some small thing Id do not know and wont let me go further.**

#include<stdio.h>
#include "libft.h"

char    *ft_itoa(int n)
{
    int i;
    int z;
    char x;
    char *itoa_buffer;

    if (n == INT_MIN)
        return(ft_strdup("-2147483648"));
    if (n < 0)
    {
        n = -n;
        z = n;
        i = 1;
    }
    else
    {
        z = n;  
        i = 0;
    }
    while(z > 0)
    {
        z = z/10;
        i++;
    }   
    if(!(itoa_buffer = (char *)malloc((i+1)*sizeof(char))))
        return(0);
    i = i + 1;
    while(--i)
    {   
        x = (n%10 + '0');
        itoa_buffer[i] = x;
        n = n/10;
        if(n == 0 && i == 2)
        {
            i--;
            itoa_buffer[i] = '-';
            i--;
            break;
        }
    }
    itoa_buffer[i] = '\0'; // it stopped showing answers when i tried to add this symbol at the end.
    return(itoa_buffer);
}

int main()
{
    int n;
    
    n = 1980;
    printf("%s", ft_itoa(n));
}

Solution

  • You are putting '\0' as the first character of the string.

    Instead of that, you should put that as the last character.

    Instead of this part

        i = i + 1;
        while(--i)
        {   
            x = (n%10 + '0');
            itoa_buffer[i] = x;
            n = n/10;
            if(n == 0 && i == 2)
            {
                i--;
                itoa_buffer[i] = '-';
                i--;
                break;
            }
        }
        itoa_buffer[i] = '\0';
    

    you should do this

        itoa_buffer[i] = '\0';
        while(i--)
        {   
            x = (n%10 + '0');
            itoa_buffer[i] = x;
            n = n/10;
            if(n == 0 && i == 1)
            {
                i--;
                itoa_buffer[i] = '-';
                break;
            }
        }