hazrmard hazrmard - 7 months ago 65
C Question

How to do one line assignment to malloc() arrays in C?

In C I can initialize an array on the stack like so:

SOME_DATA_TYPE* x = (SOME_DATA_TYPE[5]) {v1, v2, v3, v4, v5};

Is there a similar one-line method to assign values to a
-ed array on the heap?

SOME_DATA_TYPE* y = malloc(sizeof(SOME_DATA_TYPE)*5);
// what comes here?

Or do I have to iterate over the array and assign values individually?


The first issue about "initializing" the result of malloc() is that the allocation may fail. Here y is initialized to some pointer value. The data referenced it still indeterminate.

#define  element_count  5
SOME_DATA_TYPE *y = malloc(sizeof *y * element_count);
if (y == NULL) Handle_OutOfMemory();

With C11, code can use compound literals to set, not initialize, the data pointed to by y.

memcpy(y, (SOME_DATA_TYPE[element_count]) {v1, v2, v3, v4, v5}, sizeof *y * element_count);

Using a direct one-liner without checking the allocation would not be robust programming.

// one-liner, but not robust code
SOME_DATA_TYPE *y = memcpy(malloc(sizeof *y * element_count), 
    (SOME_DATA_TYPE[element_count]) {v1, v2, v3, v4, v5}, sizeof *y * element_count);

Notice code uses the sizeof *pointer_variable * element_count rather than sizeof (pointer_variable_dereferenced_type) * element_count as easier to code, less error prone, easier to review and maintain. Either approach will work.