【问题标题】:I'm trying to make a function that converts integer to string which is not returning the string. How can I solve this?我正在尝试创建一个将整数转换为不返回字符串的字符串的函数。我该如何解决这个问题?
【发布时间】:2020-08-09 02:29:30
【问题描述】:

我正在尝试使用此代码将整数转换为字符串 它正在打印值,但没有向调用函数返回任何内容

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

【问题讨论】:

标签: c function return-value


【解决方案1】:

我只是忘记了这条规则。非常感谢

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

【讨论】:

  • str 作为参数传递有什么意义?它按值传递并立即被malloc 结果覆盖。
  • num_len太小会溢出缓冲区,太大会导致字符串前面有未初始化的垃圾。调用者应该如何知道正确的值?如果调用者能搞定,为什么这个函数不能搞定,这样你就可以消除这些错误?
  • 我正在传递在调用函数中声明的字符串变量(char *)的地址,但不分配任何空间,而是在被调用函数中动态分配空间。如果我不这样做,那么调用函数就不会得到返回值
  • 无论你为str 传递的内容都会立即被覆盖,因此函数不会使用输入值,并且对于按值调用语义,它不能作为输出值。
猜你喜欢
  • 1970-01-01
  • 2015-04-23
  • 2020-05-21
  • 2021-08-10
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
相关资源
最近更新 更多