英文:
How to initialize a buffer of large size to all bits on?
问题
以下是您要翻译的内容:
我正在尝试将位图初始化为所有位都为1。我的想法是初始化一个缓冲区大小的数组,然后使用 memcpy
;然而:
#include <stdio.h>
#define SIZE 5
int main () {
int i[SIZE] = { ~0 };
for (int j = 0 ; j < SIZE ; j++) {
printf("%d\n", i[j]);
}
return 0;
}
结果是:
-1
0
0
0
0
我期望看到全部是 -1
。为什么这不起作用,我如何实现我的目标?
英文:
I am trying to initialize a bitmap to all bits on. My idea was to initialize an array of the buffer size and then use memcpy
; however:
#include <stdio.h>
#define SIZE 5
int main () {
int i[SIZE] = { ~0 };
for (int j = 0 ; j < SIZE ; j++) {
printf("%d\n", i[j]);
}
return 0;
}
results in:
-1
0
0
0
0
my expectation was that I would see all -1
. Why does this not work, and how can I accomplish my goal?
答案1
得分: 2
这:
int i[SIZE] = { ~0 };
只显式地初始化数组的第一个元素为~0
,其余的元素会隐式地被设置为0。
如果你想要所有位都被设置,你需要使用memset
:
memset(i, ~0, sizeof i);
英文:
This:
int i[SIZE] = { ~0 };
Explicitly initializes only the first element of the array to ~0
. The rest are implicitly set to 0.
If you want all bits to be set, you need to use memset
:
memset(i, ~0, sizeof i);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论