AlainD
AlainD

Reputation: 6615

Can memset be used for multi-byte types and non-zero values

I'm trying to initialise an array to a non-zero value:

BYTE byteArray[50];
memset(byteArray, 20, sizeof(byteArray));   // Works fine

int intArray[50];
memset(intArray, 20, sizeof(intArray));     // Does not work

For now, am just manually initialising the array:

// Initialise array manually
for (int pos = 0; pos < 50; pos++)
    intArray[pos] = 20;

I do appreciate that memset sets every byte in the memory range, so this cannot work the way I need for multi-byte types (except for the special case where the requested value is 0). Is there a way to coerce memset for non-zero values using multi-byte types or perhaps there is an alternate library function?

Upvotes: 3

Views: 2798

Answers (3)

user3629249
user3629249

Reputation: 16540

A very easy way to initialize an array :

int myArray[50] = {20};

which will initialize the whole array of int values to 20

Upvotes: -1

Lundin
Lundin

Reputation: 214395

In C you can initialize an array to one value like this:

#define ONE(n)   (n),
#define FIVE(n)  ONE(n) ONE(n) ONE(n) ONE(n) ONE(n)
#define TEN(n)   FIVE(n) FIVE(n)
#define FIFTY(n) TEN(n) TEN(n) TEN(n) TEN(n) TEN(n)

const int intArray [50] = { FIFTY(20) };

Or if you wish to assign it in run-time:

int intArray [50];
...
memcpy( intArray, &(int[50]){FIFTY(20)}, sizeof(intArray) );

A variable alternative that's easier to maintain:

#define I1(n)  (n),
#define I2(n)  I1(n) I1(n)
#define I3(n)  I1(n) I1(n) I1(n)
#define I5(n)  I1(n) I1(n) I1(n) I1(n) I1(n)
#define I10(n) I5(n) I5(n)
#define I50(n) I10(n) I10(n) I10(n) I10(n) I10(n)

#define INIT_FILL_ARRAY(n, val) I##n(val)

int main (void)
{
  const int intArray[] = 
  { 
    INIT_FILL_ARRAY(5, 20) 
    INIT_FILL_ARRAY(3, 10) 
    INIT_FILL_ARRAY(2, 123)
  };

  for(size_t i=0; i<sizeof intArray/sizeof *intArray; i++)
  {
    printf("%d %d\n", i, intArray[i]);
  }
}

Output:

0 20
1 20
2 20
3 20
4 20
5 10
6 10
7 10
8 123
9 123

Upvotes: 1

eerorika
eerorika

Reputation: 238401

Is there a way to coerce memset for non-zero values using multi-byte types

No.

or perhaps there is an equivalent C library function?

Not that I know of. Instead, you can use a simple loop.

But since you've tagged C++, there is an appropriate function in that standard library: std::fill or std::fill_n.

PS. memset doesn't only work with 0. It also works with all numbers with identically repeating byte pattern. Like for example ~0.

Upvotes: 6

Related Questions