sizeof和strlen
来源:互联网 发布:react.js ui 编辑:程序博客网 时间:2024/06/05 19:15
这几天一直在忙着写大作业,实现了一个哈夫曼树编解码,其中用到了像文件中写入字符对应的字符串的编码时,我是现将编码串写到一个char 类型的buf数组里,然后对该buf压缩,像buf中复制时,我使用的memcpy函数,MSDN上关于这个函数的原型是:
void *memcpy( void *dest, const void *src, size_t count);
<p class="label"><strong>Return Value</strong></p><p><strong>memcpy</strong> returns the value of <em>dest.</em></p><p class="label"><strong>Parameters</strong></p><p class="dt"><em>dest </em>New buffer</p><p class="dt"><em>src </em>Buffer to copy from</p><p class="dt"><em>count </em>Number of characters to copy</p><p class="label"><strong>Remarks</strong></p><p class="label">The <strong>memcpy</strong> function copies <em>count</em> bytes of <em>src</em> to <em>dest.</em> If the source and destination overlap, this function does not ensure that the original source bytes in the overlapping region are copied before being overwritten. Use <strong>memmove</strong> to handle overlapping regions.</p>
当最初我是这样写的
memcpy(buf, ch_code[i].codeStr, sizeof(ch_code[i].codeStr));
然后将buf中的数据写入到文件中,虽然写入的时候没有错误,但是解码的时候,直接就崩了,起初还找不到原因,只好单步调试了,当执行到这里的时候,ch_code[i]是"00001"这一句执行之后,本来预计的buf中的内容应该为"00001"但是,看到的却是"0000"这才突然想起来,是误用了sizeof。
sizeof返回一个对象或者类型的字节数,MSDN上是这么定义的
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.The expression is either an identifier or a type-cast expression (a type specifier enclosed in parentheses).When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.
总结位一下几点:
- 对于系统的基本类型,则返回该变量所对应的类型的长度
- 对于数组,则返回数组的长度
- 对于指针变量,则直接返回指针变量对于的长度(32位机中,返回4,;64位机种返回8)
- 对于结构体类型,要特别注意,字节对齐
所以当要对指针操作时,直接用strlen吧,别自己给自己挖坑了~~
将代码中相应的地方改为
memcpy(buf, ch_code[i].codeStr, strlen(ch_code[i].codeStr));再次运行,成功啦~~~
0 0
- sizeof和strlen()
- 关于sizeof 和strlen
- sizeof 和 strlen区别
- strlen 和sizeof
- sizeof 和strlen
- strlen和sizeof
- strlen和sizeof
- sizeof 和strlen
- sizeof和strlen
- sizeof和strlen
- sizeof 和 strlen
- sizeof和strlen
- strlen和sizeof
- sizeof 和 strlen()
- sizeof和strlen
- sizeof和strlen
- sizeof和strlen区别
- 浅析sizeof和strlen
- [转]榨干 PHP,不得不转的一篇PHP使用技巧!
- Flatten Binary Tree to Linked List
- 凸优化:ADMM(Alternating Direction Method of Multipliers)交替方向乘子算法系列之九: Nonconvex Problems
- [转]开发大型高负载类网站应用的几个要点
- leetcode 014 —— Longest Common Prefix
- sizeof和strlen
- 实现基于Memcache存储的Session类
- 凸优化:ADMM(Alternating Direction Method of Multipliers)交替方向乘子算法系列之十: Implementation
- 用Command实现校验器
- android studio集成友盟v2.3消息推送
- Mac上配置Ant打包工具
- 20.顺时针打印矩阵
- HtmlParser学习系列 -- 学习总结
- struts2概述