c - 将 sizeof() 用于整数数组?
问题描述
// Buffer size
#define BUFSIZE (32)
// The buffer
int buf[BUFSIZE];
// Clearing the buffer:
// 1st way
memset(buf, 0, BUFSIZE*sizeof(int));
// or
// 2nd way
memset(buf, 0, sizeof(buf));
要获得所需的缓冲区大小(以字节为单位)memset
,应该sizeof
在int
(第一种方式)或数组(第二种方式)上调用?有关系吗?
解决方案
您应该使用第二个变体。
它对数组大小或类型的更改更加健壮:如果出现以下情况,第一个变体将失败:
int buf[NEW_BUFSIZE]; // changed size
memset(buf, 0, BUFSIZE*sizeof(int)); // will partially initialize or overflow
memset(buf, 0, sizeof(buf)); // works fine
或者
new_type buf[BUFSIZE]; // changed type
memset(buf, 0, BUFSIZE*sizeof(int)); // will partially initialize or overflow
memset(buf, 0, sizeof(buf)); // works fine
顺便提一句。
sizeof
如果操作数是表达式,则无需使用括号。sizeof buf
就够了。
推荐阅读
- html - HTML/CSS(以 PDF 格式呈现)在第一页的页脚之后显示第二页
- python-3.x - 使用 TTLCache::cachetools
- python - 从 Yocto 构建 aiortc 库(Python)
- spring-boot - 如何根据任意 http 标头创建主体?
- yaml - 将值从一个文件(加密)传递给 yaml,其中包含 yaml
- python - 如何在 python 文件中设置 PYTHONHASHSEED
- python - 如何总结具有多个条件的元组列表中的最后一个数字/元素?
- javascript - IONIC 错误 TS2488:类型“对象”必须具有返回迭代器的“[Symbol.iterator]()”方法
- php - 我的自定义设置页面中的数据无法保存
- php - 如何找出 PHP (codeigniter) 网站中的恶意代码并删除这些恶意软件?