首页 > 解决方案 > 将 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,应该sizeofint(第一种方式)或数组(第二种方式)上调用?有关系吗?

标签: c

解决方案


您应该使用第二个变体。

它对数组大小或类型的更改更加健壮:如果出现以下情况,第一个变体将失败:

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就够了。


推荐阅读