问题是您的函数不知道传入的字符串的结尾。要解决此问题,您需要将您初始化char *
为 all0
或\0
. 另一个问题是您将数字错误地转换为字符。最后,这个函数没有什么安全的,因为字符串的大小没有传入,所以你只需要确保你事先分配了足够的空间。
void concat(char *str, const char *ch, int num)
{
//This is function not safe since you do not
//know how much space str has allocated
str += strlen(str);
*str = *ch; ++str;
if(num < 0)
{
*str = '-';//Add the -
++str;
num *= -1; //Make the number positive
}
//Determine the number of digits first
//because you need to add characters backwards
int digits = 0, tmpnum = num;
while (tmpnum) {
tmpnum /= 10;
++digits;
}
while(digits--)
{
str[digits] = '0' + num % 10;
num /= 10;
}
}
用法:
char *runner = new char[20]();
//or
//char *runner = (char*)calloc(20, 1);
concat(runner, "a", 10);
concat(runner, "b", 20);
concat(runner, "c", -30);
delete [] runner;
//or if you used calloc
//free(runner);
我这样做是假设这是一项家庭作业,有更简单/更安全的方法可以完成此任务,尤其是使用C++
您的问题被标记的内容。