Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use memset for initializing bufffers with values other than 0? [duplicate]

Tags:

c

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

will initialize buff with o's

But the following will not initialize buff with 5's. 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));
like image 832
user2799508 Avatar asked Jan 06 '14 13:01

user2799508


3 Answers

memset initializes bytes, not data types, to a value. So for your example…

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

… if an int is four bytes, all four bytes will be initialized to 5. Each integer will actually have a value of 0x05050505 == 84215045, not 5 as you're expecting.

If you would like to initialize each integer in your array to 5, you'll have to do it like this:

int i;
for(i = 0; i < 1000; i++)
    buff[i] = 5;
like image 128
Fiddling Bits Avatar answered Oct 11 '22 16:10

Fiddling Bits


Depending on what OS you are using you may be able to use memset_pattern4 et al, otherwise you'll just need to do it with a loop.

like image 42
Paul R Avatar answered Oct 11 '22 15:10

Paul R


I personally don't recommend memset for general initialization. There are too many things you have to be sure of to be able to correctly and portably use it. It's basically only good for char arrays or microcontroller code.

The way to initialize an array in C is the following (assume size N):

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

With C99, you can do more interesting stuff. For example, imagine the buffer is an array of the following struct:

struct something
{
    size_t id;
    int other_value;
};

Then you can initialize like this:

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

This is called designated initializer. Like all other cases of initializers, if you don't mention a specific field of the struct, it will be automatically zero initialized.

like image 1
Shahbaz Avatar answered Oct 11 '22 15:10

Shahbaz