整数转换为字符串

因为64位下INT_MAX其长度不超过20,故此处将字符串数组传递进函数。

int num2str(int num,char str[])
{
    char c;
    int i=0, j=0, k=0, tmp = num > 0 ? num : -1 * num;

    if (num > INT_MAX || num < INT_MIN) return -1;

    if (num<0)
    {
        str[i++] = '-'; ++j;
        num *= -1; //求余需要注意转换为正数,因为-1111%10==-1
    }
    else if (0==num)
    {
        str[0] = '0'; str[1] = ''; return 0;
    }

    while (tmp)
    {
        str[i] = tmp % 10 + '0';
        ++i; tmp /= 10;
    }

    k = i - 1;
    while (j<k) //字符串转换
    {
        c = str[j];
        str[j] = str[k];
        str[k] = c;
        j++; k--;
    }
    str[i] = '';

    return 0;
}

此处考虑了整数为正或为负的情况,但是存在一个问题,main里传递进的数字如果溢出,则函数中的数字截然不同。

在程序员面试宝典靠中问题:为什么

char* strcpy(char* strDest, const char* strSrc)

要返回char*,不是已经复制了吗?

答:构造链式表达式,诸如

int len = strlen(strcpy(strDest, "hello world"));
原文地址:https://www.cnblogs.com/jason1990/p/4675044.html