C语言 在 C 中对整数数组使用 memset

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17288859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:46:50  来源:igfitidea点击:

Using memset for integer array in C

cmemset

提问by user1762571

char str[] = "beautiful earth";
memset(str, '*', 6);
printf("%s", str);

Output:
******ful earth

Like the above use of memset, can we initialize only a few integer array index values to 1 as given below?

像上面的 memset 使用一样,我们可以像下面给出的那样只将几个整数数组索引值初始化为 1 吗?

int arr[15];
memset(arr, 1, 6);

回答by Jonathon Reinhart

No, you cannot use memset()like this. The manpagesays (emphasis mine):

不,你不能这样使用memset()。该手册页说(重点煤矿):

The memset()function fills the first nbytesof the memory area pointed to by swith the constant byte c.

memset()功能填充第一n字节由指向的存储器区域的s具有恒定字节c

Since an intis usually 4 bytes, this won't cut it.

由于 anint通常是 4 个字节,所以这不会削减它。



If you (incorrectly!!) try to do this:

如果您(错误地!!)尝试这样做:

int arr[15];
memset(arr, 1, 6*sizeof(int));    //wrong!

then the first 6 ints in the array will actually be set to 0x01010101 = 16843009.

那么int数组中的前 6秒实际上将设置为 0x01010101 = 16843009。

The only time it's ever really acceptable to write over a "blob" of data with non-byte datatype(s), is memset(thing, 0, sizeof(thing));to "zero-out" the whole struture/array. This works because NULL, 0x00000000, 0.0, are all completely zeros.

用非字节数据类型写入“blob”数据的唯一一次真正可以接受的是memset(thing, 0, sizeof(thing));将整个结构/数组“归零”。这是有效的,因为 NULL、0x00000000、0.0 都是完全零。



The solution is to use a forloop and set it yourself:

解决方案是使用for循环并自行设置:

int arr[15];
int i;

for (i=0; i<6; ++i)    // Set the first 6 elements in the array
    arr[i] = 1;        // to the value 1.

回答by vidit

Short answer, NO.

简短的回答,不。

Long answer, memsetsets bytes and works for characters because they are single bytes, but integers are not.

长答案,memset设置字节并适用于字符,因为它们是单字节,但整数不是。

回答by mattn

The third argument of memset is byte size. So you should set total byte size of arr[15]

memset 的第三个参数是字节大小。所以你应该设置总字节大小arr[15]

memset(arr, 1, sizeof(arr));

However probably, you should want to set value 1 to whole elements in arr. Then you've better to set in the loop.

但是很可能,您应该将值 1 设置为 arr 中的整个元素。那么你最好在循环中设置。

for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) {
    arr[i] = 1;
}

Because memset()set 1 in each bytes. So it's not your expected.

因为memset()在每个字节中设置 1。所以这不是你的预期。

回答by ceilingcat

On Linux, OSX and other UNIX like operating systems where wchar_tis 32 bits and you can use wmemset()instead of memset().

在Linux,OSX和其他UNIX类操作系统,其中wchar_t的32位,你可以使用wmemset()的替代memset()

#include<wchar.h>
...
int arr[15];
wmemset( arr, 1, 6 );

Note that wchar_ton MS-Windows is 16 bits so this trick may not work.

请注意,wchar_t在 MS-Windows 上是 16 位,所以这个技巧可能不起作用。

回答by i Code 4 Food

Since nobody mentioned it...

既然没人提...

Although you cannot initialize the integers with value 1using memset, you caninitialize them with value -1and simply change your logic to work with negative values instead.

虽然您不能1使用 memset用 value 初始化整数,但您可以用 value 初始化它们,-1只需更改逻辑以使用负值。

For example, to initialize the first 6 numbers of your array with -1, you would do

例如,要使用 初始化数组的前 6 个数字-1,您可以这样做

memset(arr,-1,6*(sizeof int));

Furthermore, if you only need to do this initialization once, you can actually declare the array to start with values 1from compile time.

此外,如果您只需要进行一次初始化,您实际上可以将数组声明为1从编译时开始的值。

int arr[15] = {1,1,1,1,1,1};

回答by AnT

No, you can't [portably] use memsetfor that purpose, unless the desired target value is 0. memsettreats the target memory region as an array of bytes, not an array of ints.

不,您不能 [可移植地]memset用于该目的,除非所需的目标值为0. memset将目标内存区域视为字节数组,而不是ints数组。

A fairly popular hack for filling a memory region with a repetitive pattern is actually based on memcpy. It critically relies on the expectation that memcpycopies data in forward direction

使用重复模式填充内存区域的一种相当流行的技巧实际上是基于memcpy. 它严重依赖memcpy于向前复制数据的期望

int arr[15];

arr[0] = 1;
memcpy(&arr[1], &arr[0], sizeof arr - sizeof *arr);

This is, of course, a pretty ugly hack, since the behavior of standard memcpyis undefined when the source and destination memory regions overlap. You can write your own version of memcpythough, making sure it copies data in forward direction, and use in the above fashion. But it is not really worth it. Just use a simple cycle to set the elements of your array to the desired value.

当然,这是一个非常丑陋的 hack,因为memcpy当源和目标内存区域重叠时,标准的行为是未定义的。您可以编写自己的版本memcpy,确保它向前复制数据,并以上述方式使用。但这并不值得。只需使用一个简单的循环将数组的元素设置为所需的值。

回答by ganjaam

I tried the following program and it appears that you can initialize your array using memset() with -1 and 0 only

我尝试了以下程序,看来您只能使用带有 -1 和 0 的 memset() 初始化数组

#include<stdio.h>
#include<string.h>

void printArray(int arr[], int len)
{
        int i=0;
    for(i=0; i<len; i++)
    {
        printf("%d ", arr[i]);
    }
    puts("");
}

int main()
{
    int arrLen = 15;
    int totalNoOfElementsToBeInitialized = 6;

    int arr[arrLen];
    printArray(arr, arrLen);
    memset(arr, -1, totalNoOfElementsToBeInitialized*sizeof(arr[0]));
    printArray(arr, arrLen);
    memset(arr, 0, totalNoOfElementsToBeInitialized*sizeof(arr[0]));
    printArray(arr, arrLen);
    memset(arr, 1, totalNoOfElementsToBeInitialized*sizeof(arr[0]));
    printArray(arr, arrLen);
    memset(arr, 2, totalNoOfElementsToBeInitialized*sizeof(arr[0]));
    printArray(arr, arrLen);
    memset(arr, -2, totalNoOfElementsToBeInitialized*sizeof(arr[0]));
    printArray(arr, arrLen);
    return 0;
}

回答by akD

Ideally you can not use memset to set your arrary to all 1.
Because memsetworks on byte and set every byte to 1.

理想情况下,您不能使用 memset 将数组设置为全部 1。
因为memset对字节起作用并将每个字节设置为 1。

memset(hash, 1, cnt);

So once read, the value it will show 16843009 = 0x01010101 = 1000000010000000100000001
Not 0x00000001
But if your requiremnt is only for bool or binary value then we can set using C99 standard for C library

因此,一旦读取,它将显示的值16843009 = 0x01010101 = 1000000010000000100000001
不是0x00000001
但是如果您的要求仅适用于布尔值或二进制值,那么我们可以使用 C99 标准为 C 库设置

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>        //Use C99 standard for C language which supports bool variables

int main()
{
    int i, cnt = 5;
    bool *hash = NULL;
    hash = malloc(cnt);

    memset(hash, 1, cnt);
    printf("Hello, World!\n");

    for(i=0; i<cnt; i++)
        printf("%d ", hash[i]);

    return 0;
}

Output:

输出:

Hello, World!
1 1 1 1 1

你好,世界!
1 1 1 1 1

回答by Himanshu Singhvi

Memset sets values for data types having 1 byte but integers have 4 bytes or more , so it won't work and you'll get garbage values. It's mostly used when you are working with char and string types.

Memset 为具有 1 个字节但整数具有 4 个字节或更多字节的数据类型设置值,因此它不起作用并且您将获得垃圾值。它主要用于处理 char 和 string 类型。

回答by user3210859

memset((char *)&tab, 0, sizeof(tab));