How to use memset to initialize buffers with values ​​other than 0?

int buff[1000] 
memset(buff, 0, 1000 * sizeof(int));

will initialize buff with o

But the following will not initialize the buff with 5. So, what is the way to achieve this using memset in C (not in C ++)? I want to use memset for this purpose.

int buff[1000] 
memset(buff, 5, 1000 * sizeof(int));
+4
source share
4 answers

memsetinitializes bytes, not data types, to a value. So for your example ...

int buff[1000] 
memset(buff, 5, 1000 * sizeof(int));

... if a intis four bytes, all four bytes will be initialized to 5. Each integer will have a value 0x05050505 == 84215045, not 5what you expect.

If you want to initialize every integer in your array to 5, you need to do it like this:

int i;
for(i = 0; i < 1000; i++)
    buff[i] = 5;
+7
source
+1

memset . , , . char .

C ( N):

for (i = 0; i < N; ++i)
    buff[i] = init_value;

C99 . , , :

struct something
{
    size_t id;
    int other_value;
};

:

for (i = 0; i < N; ++i)
    buff[i] = (struct something){
        .id = i
    };

. , , .

+1
source

If buff is not an array of bytes, you can initialize it only with values ​​that consist of repeating hexadecimal values ​​using memset (e.g. -1, 0x01010101, etc.)

One way to do this is to use memcpyit this way:

buff[0] = 5;
memcpy(buff + 1, buff, sizeof(buff) - sizeof(*buff))

HOWEVER , it depends on undefined behavior and may or may not work on your system.

A decent compiler should create a fairly efficient loop from

for (i = 0; i < 1000; i++) buff[i] = 5;
0
source

All Articles