简体   繁体   中英

I'm trying to make a function that converts integer to string which is not returning the string. How can I solve this?

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM