一道笔试题,将字符串逆序。
- #include <stdio.h>
-
#include <assert.h>
-
#include <malloc.h>
-
#include <string.h>
-
-
/*
-
** 函数名:str_reverse
-
** 输入参数:char *str:原字符串
-
** 返回值:char *ret_char:逆序后的字符串
-
** 功能:将字符串逆序,如将"abcdef"转换成"fedcba"
-
*/
-
char *str_reverse(char* str)
-
{
-
int i=strlen(str);
-
char *temp = (char *)malloc(sizeof(str)); //在堆区(heap)为temp分配内存,存储逆序后的字符串
-
if(NULL == temp) //检测是否分配成功
-
return NULL;
-
char *ret_char = temp;//返回值,存储逆序后的字符串的首地址
-
-
while(*str) //将str指向字符串尾部'\0'字符
-
str++;
-
str--; //将str指向字符串最后一个字符
-
-
while(i--)
-
*temp++ = *str--;
-
-
return ret_char;
-
}
-
-
int main()
-
{
-
char *a="abcdef";
-
char *b=NULL;
-
b = str_reverse(a);
-
printf("%s \n",b);
-
return 0;
-
}