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));
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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With