02. 请找出下面代码中的错误,并完成倒序操作。
#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是系统内置,所以引用应该是<string.h>
malloc等函数声明在<stdlib.h>
2. 主函数
既然有返回值(0),那么一定是int main()
二、编写程序
两种思路:使用字符串和使用数组
注意: 字符串结尾都要加个“\0”
1. 使用字符串
/* * ft1202.c * * Created on: 2012-11-5 * Author: xiaobin * * Huawei face questions */ #include <stdio.h> #include <string.h> #include <stdlib.h> 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)。
/* * ft1202.c * * Created on: 2012-11-5 * Author: xiaobin * * Huawei face questions */ #include <stdio.h> #include <string.h> #include <stdlib.h> 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; }
/* * ft1202.c * * Created on: 2012-11-5 * Author: xiaobin * * Huawei face questions */ #include <stdio.h> #include <string.h> #include <stdlib.h> 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; }