野火电子论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 285673|回复: 1267

【每日一思】考验阅读代码的分析能力

  [复制链接]
发表于 2013-12-11 00:50:35 | 显示全部楼层 |阅读模式
出了 每日一题那么久,相信大家的C语言也有了个更加深入的了解了吧?
我们的 题目,呵呵,也出得差不多了,接下来,我们 锻炼一下分析代码的能力!

  1. char *func(char *dest, const char *src, int count)   
  2. {   
  3.     char *tmp = dest;   
  4.         
  5.     while (count) {   
  6.         if ((*tmp = *src) != 0)   
  7.             src++;   
  8.         tmp++;   
  9.         count--;   
  10.     }   
  11.         
  12.     return dest;   
  13. }   

  14. //请解析 上述 代码的执行功能
复制代码
大家认真去思考,直接看答案是 学不到东西的,认真回答一下问题。 这些题目都是 找工作时面试笔试常考的问题,当然,往往是叫你自己写出源代码。

答案依旧回复可见。


  1. 直接上源代码
  2. /*   
  3. * strncpy - Copy a length-limited, %NUL-terminated string   
  4. * @dest: Where to copy the string to   
  5. * @src: Where to copy the string from   
  6. * @count: The maximum number of bytes to copy   
  7. *   
  8. * The result is not %NUL-terminated if the source exceeds   
  9. * @count bytes.   
  10. *   
  11. * In the case where the length of @src is less than that of   
  12. * count, the remainder of @dest will be padded with %NUL.   
  13. */   
  14. char *strncpy(char *dest, const char *src, size_t count)    //从 src 复制count个字符 到 dest
  15. {   
  16.     char *tmp = dest;   
  17.         
  18.     while (count) {   
  19.         if ((*tmp = *src) != 0)    //把 src 的值 复制到 dest ,如果 src 的值 非空,那么指针自加。
  20.                                    //否则 指针不加,src 后续都是指向 0 ,即字符串结束,后续的 dest值都为 0
  21.             src++;   
  22.         tmp++;                     // dest 的指针 自加
  23.         count--;                   //最大计数值 减 1
  24.     }   
  25.         
  26.     return dest;   
  27. }   
复制代码

回复

使用道具 举报

 楼主| 发表于 2013-12-11 13:39:58 | 显示全部楼层
Waiting 发表于 2013-12-11 11:28
首先定义了一个函数指针func包含三个参数:返回char型值的指针变量dest,只读型的返回char型值的指针变量sr ...

漏了个把dest后面的数据清0这个没讲
回复 支持 反对

使用道具 举报

 楼主| 发表于 2013-12-25 15:37:02 | 显示全部楼层
xinxin 发表于 2013-12-25 15:34
从SRC中复制count个字符到dest中,不知道是否对,蒙的笑坏我的肚子了

漏了 后面 清 0操作
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

联系站长|手机版|野火电子官网|野火淘宝店铺|野火电子论坛 ( 粤ICP备14069197号 ) 大学生ARM嵌入式2群

GMT+8, 2024-4-25 13:19 , Processed in 0.035733 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表