华为面试题解析 - 02
2013-11-06 23:24
441 查看
02. 请找出下面代码中的错误,并完成倒序操作。
一、明显错误
1. 头文件
string.h是系统内置,所以引用应该是<string.h>
malloc等函数声明在<stdlib.h>
2. 主函数
既然有返回值(0),那么一定是int main()
二、编写程序
两种思路:使用字符串和使用数组
注意: 字符串结尾都要加个“\0”
1. 使用字符串
更简便写法:
在“while”循环处,可以:*d++ = *(src + len)。
2. 使用数组
#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; }
2. 使用数组
/* * 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; }
相关文章推荐
- 华为面试题解析 - 06
- 华为面试题解析 - 08
- 华为面试题解析 - 03
- .NET面试题解析(02)-拆箱与装箱
- 华为面试题解析 - 07
- 华为面试题解析 - 05
- 华为面试题解析 - 10
- 华为面试题解析 - 09
- 华为面试题解析 - 04
- 华为面试题解析 - 01
- 华为面试题:从1开始将数据无限制的打印下去(c语言版)
- 华为(2007年3月)一道面试题: c语言判断一个正整数, 是否是一个对称数
- BAT Android工程师面试流程解析+还原最真实最完整的一线公司面试题
- 大数据面试-02-大数据工程师面试题
- android面试题总结02 在android中本地写入一个xml文件
- C语言面试题大汇总之华为面试题
- [java]中兴,华为面试题
- 华为面试题
- 尝试解析js面试题(二)
- 程序员面试题精选100题(02)-设计包含min函数的栈[数据结构]