为什么“memset(arr, -1, sizeof(arr)/sizeof(int))"?不将整数数组清除为-1? [英] Why does "memset(arr, -1, sizeof(arr)/sizeof(int))" not clear an integer array to -1?

查看:17
本文介绍了为什么“memset(arr, -1, sizeof(arr)/sizeof(int))"?不将整数数组清除为-1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

难道不能在整数数组上使用 memset 吗?我尝试了以下 memset 调用,但没有在 int 数组中获得正确的整数值.

Is it not possible to use memset on an array of integers? I tried the following memset call and didn't get the correct integer values in the int array.

int arr[5];
memset (arr, -1, sizeof(arr)/sizeof(int));

我得到的值是:

arr[0] = -1
arr[1] = 255
arr[2] = 0
arr[3] = 0
arr[4] = 0

推荐答案

改成memset(arr, -1, sizeof(arr));

请注意,对于 0 和 -1 以外的其他值,这将不起作用,因为 memset 为后面的 num 个字节设置从 *ptr 指示的变量开始的内存块的字节值.

Note that for other values than 0 and -1 this would not work since memset sets the byte values for the block of memory that starts at the variable indicated by *ptr for the following num bytes.

void * memset ( void * ptr, int value, size_t num );

并且由于 int 表示在多个字节上,因此您将无法获得数组中整数的所需值.

And since int is represented on more than one byte, you will not get the desired value for the integers in your array.

例外情况:

  • 0 是一个例外,因为如果将所有字节设置为 0,则该值将为零
  • -1 是另一个例外,因为 Patrick 强调 -1 在 int8_t 中是 0xff (=255),在 int32_t 中是 0xffffffff

你得到的原因:

arr[0] = -1
arr[1] = 255
arr[2] = 0
arr[3] = 0
arr[4] = 0

是因为,在您的情况下,int 的长度为 4 个字节(32 位表示),数组的字节长度为 20(=5*4),并且您仅将 5 个字节设置为 -1(=255) 而不是 20.

Is because, in your case, the length of an int is 4 bytes (32 bit representation), the length of your array in bytes being 20 (=5*4), and you only set 5 bytes to -1 (=255) instead of 20.

这篇关于为什么“memset(arr, -1, sizeof(arr)/sizeof(int))"?不将整数数组清除为-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆