使用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所需的缓冲区的字节大小,应该在int(第一种方式)或在数组(第二种方式)上调用sizeof?这有关系吗?

您应该使用第二个变体

对于数组大小或类型的改变更加健壮:如果:

第一个变量将失败
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足以.

我将使用第一个。因为如果你改变

的分配
int buf[BUFSIZE];

int *buf = malloc(BUFSIZE * sizeof*buf);

则第二个(sizeof buf)没有给出数组的大小。

为了避免依赖(buf知道它的内容类型,即使是指针)和父元素:

memset(buf, 0, BUFSIZE * sizeof*buf)

大小: BUF可能会产生误导,因为它是元素的数量,而不是sizeof-array-size。LEN(GTH)是另一种选择。

最新更新