sizeof和strlen

这几天一直在忙着写大作业,实现了一个哈夫曼树编解码,其中用到了像文件中写入字符对应的字符串的编码时,我是现将编码串写到一个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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值