Search code examples
cinitializationmemset

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));

Solution

  • 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.