fabricemarcelin
fabricemarcelin

Reputation: 1749

Alternative to memset

I want to initialize an array of struct, however the second parameter of memset() takes an int. Is there another the function that does the same but with a (void *) has 2nd parameter? I thought of memcpy() but it doesn't set the value in the entire array. Any idea?

the struct:

typedef struct {
    int x;
    int y;
    char *data;
} my_stuff;

The code:

my_stuff my_array[];
my_array = malloc(MAX * sizeof(my_stuff));

my_stuff *tmp;
tmp->x = -1;
tmp->y = 1;
strcpy(tmp->data = "Initial state");

memset(my_array, tmp, sizeof(my_array));

Upvotes: 1

Views: 15300

Answers (3)

BiGYaN
BiGYaN

Reputation: 7159

You cannot use memset() in this case. You should use memcpy(). Just try this out: 1. malloc your array 2. initialize the first element of the array 3. copy the first element to all the elements

/* step 1 */
my_stuff *my_array = malloc(MAX * sizeof(my_stuff));
int i;

/* step 2 */
my_array[0].x = -1;
my_array[0].y = 1;
my_array[0].data = "Initial state";

/* step 3 */
for (i = 1; i < MAX; i++)
    memcpy(&my_array[i], &my_array[0], sizeof(my_array[0]));

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67175

memset() sets the value of each byte. There's no problem typecasting a pointer to an integer (the second parameter). The main problem is that it will be bigger than a byte.

I'm not aware of any version of memset() that copies more than byte values. I would create a simple loop for this.

Also note that there would be some additional problems with your code, had it worked. For one thing, sizeof(my_array) returns the total number of bytes in the data structure and not the number of elements. Also, your code would've just copied the pointer. You need to actually copy the data it points to since the target is not pointers--it's actual structures.

Upvotes: 4

caf
caf

Reputation: 239011

There isn't a standard function for this - you will just need to call memcpy() in a loop:

my_stuff *my_array = malloc(MAX * sizeof(my_stuff));
my_stuff tmp;
size_t i;

tmp.x = -1;
tmp.y = 1;
tmp.data = "Initial state";

for (i = 0; i < MAX; i++)
    memcpy(&my_array[i], &tmp, sizeof tmp);

Note that you can't strcpy() into tmp.data, because that's just a dangling pointer with no memory allocated.

Upvotes: 4

Related Questions