[cpp]
#include "string.h"
main()
{
char *src = "hello,world";
char *dest = NULL;
int len = strlen(src);
dest = (char *)malloc(len);
char *d = dest;
char *s = &src[len - 1];
while (len-- != 0)
d++ = s--;
printf("%s", dest);
return 0;
}
一、明显错误
1. 头文件
string.h是
系统内置,所以引用应该是
malloc等函数声明在
2. 主函数
既然有返回值(0),那么一定是int main()
二、编写程序
两种思路:使用字符串和使用数组
注意: 字符串结尾都要加个“\0”
1. 使用字符串
[cpp]
/*
* ft1202.c
*
* Created on: 2012-11-5
* Author: xiaobin
*
* Huawei face questions
*/
#include
#include
#include
int main(int argc, char* argv[])
{
char *src = "hello,world";
int len = strlen(src);
char *dest = NULL;
dest = (char *)malloc(len + 1); // standard: 要为'\0'分配一个空间
char *d = dest;
char *s = &src[len - 1]; // standard: 指向最后一个字符
while (len-- != 0) {
*d++ = *s--; // standard:
}
*d = 0; // standard: 尾部要加0
printf("%s\n", dest);
free(dest); // standard: 使用完,应当释放空间,以免造成内存汇泄露
return 0;
}
更简便写法:
在“while”循环处,可以:*d++ = *(src + len)。
[cpp]
/*
* ft1202.c
*
* Created on: 2012-11-5
* Author: xiaobin
*
* Huawei face questions
*/
#include
#include
#include
int main(int argc, char* argv[])
{
char *src = "hello,world";
int len = strlen(src);
char *dest = NULL;
dest = (char *)malloc(len + 1);
char *d = dest;
while (len-- != 0) {
*d++ = *(src + len); // one way
}
*d = 0;
printf("%s\n", dest);
free(dest);
return 0;
}
2. 使用数组
[cpp]
/*
* ft1202.c
*
* Created on: 2012-11-5
* Author: xiaobin
*
* Huawei face questions
*/
#include
#include
#include
int main(int argc, char* argv[])
{
char *src = "hello,world";
int len = strlen(src);
char *dest = NULL;
dest = (char *)malloc(len + 1);
/* Two way */
int i = 0;
while (len-- != 0) {
dest[i] = src[len];
i++;
}
printf("%s\n", dest);
free(dest);
return 0;
}