读书人

请问编程题:编写一个函数作用是把一

发布时间: 2013-03-21 10:08:17 作者: rapoo

请教编程题:编写一个函数,作用是把一个char组成的字符串循环右移n个。比如原来是“abcdefghi”如果n=2,移位后应该是“hiabcdefgh”
请教编程题:编写一个函数,作用是把一个char组成的字符串循环右移n个。比如原来是“abcdefghi”如果n=2,移位后应该是“hiabcdefgh”
//pStr是指向以'\0'结尾的字符串的指针
//steps是要求移动的n

void LoopMove ( char * pStr, int steps )
{
 //请填充...
}

答案1:
void LoopMove ( char *pStr, int steps )
{
 int n = strlen( pStr ) - steps;
 char tmp[MAX_LEN];
 strcpy ( tmp, pStr + n );
 strcpy ( tmp + steps, pStr);
 *( tmp + strlen ( pStr ) ) = '\0';
 strcpy( pStr, tmp );
}
答案2:
void LoopMove ( char *pStr, int steps )
{
 int n = strlen( pStr ) - steps;
 char tmp[MAX_LEN];
 memcpy( tmp, pStr + n, steps );
 memcpy(pStr + steps, pStr, n );
 memcpy(pStr, tmp, steps );
}

运行到红色字符的时候就程序崩溃了
求大侠解答。

[解决办法]


void LoopMove (char *pStr, int steps )
{
int n = strlen( pStr ) - steps;
char tmp[10];
strcpy ( tmp, pStr + n );
strcpy ( tmp + steps, pStr); --》越界了。 steps==2时,这里执行完后tmp为ghabcdefgh 共10个字符,最后还加上一个'\0',11个,超过了tmp[10]。把tmp数组改大点再试试
*( tmp + strlen (pStr)) ='\0';
strcpy( pStr, tmp );
}

读书人网 >C语言

热点推荐