Andrei Tita 已经向您展示了您在使用 NULL 终止符时遇到的问题。我将向您展示一种替代方法,以便您可以比较和对比不同的方法:
int intToStr(unsigned int num, char *s)
{
// We use this index to keep track of where, in the buffer, we
// need to output the current character. By default, we write
// at the first character.
int idx = 0;
// If the number we're printing is larger than 10 we recurse
// and use the returned index when we continue.
if(num > 9)
idx = intToStr(num / 10, s);
// Write our digit at the right position, and increment the
// position by one.
s[idx++] = '0' + (num %10);
// Write a terminating NULL character at the current position
// to ensure the string is always NULL-terminated.
s[idx] = 0;
// And return the current position in the string to whomever
// called us.
return idx;
}
您会注意到,我的替代方案还返回了它输出到缓冲区的字符串的最终长度。
祝你的课程工作顺利!