简体   繁体   English

我正在尝试制作一个 function 将 integer 转换为不返回字符串的字符串。 我该如何解决这个问题?

[英]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我正在尝试使用此代码将整数转换为字符串它正在打印值但没有向调用 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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