昨天面试腾讯,让用C语言实现将int类型转化为字符串,不使用已有的转换函数。
写代码的过程中出现了许多错误,记录一下,函数原型是面试官给出的。(原型的一些缺陷应该是面试官设的陷阱,我自己太弱都掉进去了。。。)
实现代码如下
#include <stdio.h>
#include <math.h>
#define INT_MAX 2147483647
#define INT_MIN (-2147483647-1)//必须是这种表示形式,-2147483648会报错
const char* int_to_str(int iVal)
{
static char str[12];
int isNegative = 0;
int i = 0,j=0;
if (iVal == 0)
{
str[0] = '0';
str[1] = '\0';
return str;
}
if (iVal == INT_MIN)
{
int_to_str(iVal + 1);
char *tmp = str;
while (*tmp != '\0')
tmp++;
tmp--;
*tmp += 1;
return str;
}
if (iVal < 0)
{
iVal *= -1;
isNegative = 1;
str[i++] = '-';
j++;
}
while (iVal)
{
str[i++]=iVal % 10+'0';
iVal /= 10;
}
str[i--] = '\0';
while (j < i)
{
char ch = str[i];
str[i--] = str[j];
str[j++] = ch;
}
return str;
}
int main(void)
{
printf("%s ", int_to_str(2147483647));
printf("%s ", int_to_str(-2147483647-1));
return 0;
}
自己的思考:因为原型给的返回类型为char* ,若在程序里直接定义为char * str, 函数返回后str指向的内存会被释放,str指向的内容将是无意义的,因此应把它设为static。但此时每次调用printf("%s %s ", int_to_str(123), int_to_str(-123));输出结果将是123 123,因为它们返回str是一个地址,参数从右往左计算,最后str存的值就是123,因此这种实现方式有缺陷。当使用malloc分配内存时,printf("%s ", int_to_str(2147483647));后分配的内存没有被free,造成资源泄漏。
因此在实现这种函数的原型时,应用itoa函数原型的形式,把存的地址传进去,char *itoa( int value, char *string,int radix);
原型说明:
value:欲转换的数据。
string:目标字符串的地址。
radix:转换后的进制数,可以是10进制、16进制等。