首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请问编程题:编写一个函数,作用是把一个char组成的字符串循环右移n个。比如原来是“abcdefghi”如果n=2,移位后应该是“hiabcdefgh”

2013-03-21 
请教编程题:编写一个函数,作用是把一个char组成的字符串循环右移n个。比如原来是“abcdefghi”如果n2,移位后

请教编程题:编写一个函数,作用是把一个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 );
}
 

热点排行