如何初始化一个大尺寸的缓冲区,使其所有位都设置为1?

huangapple go评论68阅读模式
英文:

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 &lt;stdio.h&gt;

#define SIZE 5

int main () {
  int i[SIZE] = { ~0 };
  for (int j = 0 ; j &lt; SIZE ; j++) {
	printf(&quot;%d\n&quot;, 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);

huangapple
  • 本文由 发表于 2023年5月21日 01:51:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296622.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定