-2

I'm trying this code to convert integers to string It's printing the values but isn't returning anything to the calling function

char* itoa(int num, int num_len)
{
    char str[num_len+2];
    int i;
    //if the num is 0
    if(num == 0)
        strcpy(str, "0");
    //if the num is negetive then we append a '-' sign at the beginning
    //and put '\0' at (num_len+1)th position 
    else if(num < 0)
    {
        num *= -1;
        str[num_len+1] = '\0';
        str[0] = '-';
        i = num_len+1;
    }
    //we put '\0' (num_len)th position i.e before the last position
    else
    {
        str[num_len] = '\0';
        i = num_len;
    } 

    for(;num>0;num/=10,i--)
    {
        str[i] = num%10 + '0';
        printf("%c ",str[i]);//for debugging
    }

    return str;
}
  • You are looking for this https://stackoverflow.com/a/8257728 – Anshuman Apr 25 '20 at 13:53
  • 1
    Does this answer your question? [How to convert an int to string in C?](https://stackoverflow.com/questions/8257714/how-to-convert-an-int-to-string-in-c) – Anshuman Apr 25 '20 at 13:53

1 Answers1

0

I just forgot that rule. thank you very much

char* itoa(int num, int num_len,char* str)
{
    int i;
    str = (char*)malloc((num_len + 2)*sizeof(char)); 
    if(num == 0)
        strcpy(str, "0");
    else if(num < 0)
    {
        num *= -1;
        str[num_len+1] = '\0';
        str[0] = '-';
        i = num_len;
    }
    else
    {
        str[num_len] = '\0';
        i = num_len-1;
    } 

    for(;num>0;num/=10,i--)
    {
        str[i] = num%10 + '0';
        printf("%c ",str[i]);
    }

    return str;
}
  • What is the point of passing `str` as an argument? It is passed by value and immediately overwritten with the `malloc` result. – pat Apr 25 '20 at 14:40
  • 1
    When `num_len` is too small, you overflow the buffer, and when it's too large, you will have uninitialized garbage at the front of the string. How is the caller supposed to know the right value? If the caller can figure it out, why can't this function do it so you can eliminate these errors? – pat Apr 25 '20 at 14:44
  • I'm passing the address of a string variable(char *) which is declared in the calling function but not allocating any space rather allocating space in the called function dynamically. If I don't do this then the calling function doesn't get the returned value – Surojit Jana Apr 26 '20 at 13:27
  • Whatever you pass in for `str` is immediately overwritten, so the input value is not used by the function, and with call by value semantics, it does not work as an output value. – pat Apr 26 '20 at 15:21