使用memset和int值来初始化整数数组-失败

4

我正在为一个CUDA程序编写主机代码,因此我必须使用标准C函数。 我在使用memset函数初始化整数数组的元素时遇到了问题。 我曾以为可以使用memset函数将整数数组初始化为所有4个元素,例如:

memset(array, 4, sizeof(array));

但是,这实际上会将数组中每个字节的值都设置为4,而不是将每个元素设置为4。 要正确地初始化数组,您需要使用循环或显式地为每个元素赋值。

int num_elements = 10;
int* array_example = (int*)malloc(num_elements * sizeof(int));
memset(array_example, 4, sizeof(array_example));

但是当我这样做时,它会将每个字节而不是每个int设置为4。如果我这样说:

memset(array_example, 4, 1);

I get a 4 in the first integer and if I say:

memset(array_example, 4, 2);

我在第一个整数中得到了1024,在第二个整数中得到了0。我知道memset函数会将第三个参数指定的字节数设置为4,但是否有办法使用memset将每个整数设置为4而不是每个字节?否则,我是否必须使用for循环?我的GPU计算能力较低,因此我无法访问一些更好的CUDA附加功能,这些功能允许更多的C++用法。

4个回答

4
如果您知道表的大小并且想将每个元素设置为特定值,您可以始终编写以下内容:
int array[10] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 };

如果您使用gcc,也可以按照以下方式操作:
int array[10] = {[0 ... 9] = 4};

当您需要动态分配数组时,我怀疑除了使用简单的循环外,没有其他解决方案。


4

我想增加一个选项并贡献一些观点:

  1. If you're working in C++ rather than C, try using std::fill(), which is generic - and let the compiler worry about the optimization:

     std::fill_n(my_array, array_length, constant_value);
    
  2. The signature of memset() is:

     void *memset(void *s, int c, size_t n);
    

    while it supposedly takes an int, it actually expects a(n unsigned) byte value (i.e. between 0 and 0xFF).

  3. Continuing tool's answer - some useful memset'ing you can do which amounts to using (unsigned) ints is setting arrays to either 0 or to UINT_MAX, i.e. to 0xFFFF or 0xFFFFFFFF etc. depending on sizeof(unsigned).

  4. If we had strided memset(), you could apply four of these to get 4-byte ints set into an array. However, we don't, and in fact it seems there's currently no advantage to doing that over just looping.


3

在表示int值的位模式具有逐字节恒定的模式的情况下(例如2补码),可以成功地使用memset(不是幸运的问题)。

例如,如果您使用4填充数组,则每个int将初始化为0x04040404(考虑sizeof(int)= 32),这可能是可以的,也可能不可以,这取决于您的需求。

这适用于整数初始化值的许多特定值。

但这导致代码几乎无法移植。

如果要将每个int初始化为零,则应始终起作用。


2

没有标准的替代函数可以像memset一样写入整数。您需要编写一个循环。


好的,谢谢。我继承了一个5000多行的医学成像研究程序,他们在各个地方都使用了memset,仿佛它可以初始化每个整数。他们的代码能够正常工作,所以我一直在尝试弄清楚是否有什么我错过的东西,或者他们幸运地覆盖了垃圾初始化。 - Blake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接