Intializing dynamic arrays in c

Viewed 57

I've created a dynamic array using malloc, while initializing it, I'm getting an error. What am I doing wrong here?

float* data_input = malloc(4 * sizeof(float));
data_input = {1.2, 2.4, 3.2, 4.5};

Error:

model.c: In function ‘main’:
model.c:9:18: error: expected expression before ‘{’ token
    9 |     data_input = {1.2, 2.4, 3.2, 4.5};
3 Answers

This assignment statement

data_input = {1.2, 2.4, 3.2, 4.5};

is incorrect in C.

Instead you could write

#include <stdlib.h>
#include <string.h>

//...

float* data_input = malloc(4 * sizeof(float));
memcpy( data_input, ( float [] ){1.2, 2.4, 3.2, 4.5 }, sizeof( float[4] ) );

Here is a demonstrative program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
    enum { N = 4 };
    
    float *data_input = malloc( N * sizeof( float ) );
    memcpy( data_input, ( float [] ){1.2, 2.4, 3.2, 4.5 }, sizeof( float[N] ) );
    
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%.1f ", data_input[i] );
    }
    
    putchar( '\n' );
    
    free( data_input );

    
    return 0;
}

The program output is

1.2 2.4 3.2 4.5 

There is no syntax in C in which {1.2, 2.4, 3.2, 4.5} denotes an array.

In initializations, {1.2, 2.4, 3.2, 4.5} denotes a list of initializers which may be used to initialize the elements of an array.

After float *data_input = malloc(4 * sizeof *data_input); (and checking that the return value of malloc is not a null pointer), you can initialize the array by initializing each element individually:

data_input[0] = 1.2;
data_input[1] = 2.4;
data_input[2] = 3.2;
data_input[3] = 4.5;

or you can copy the array from a compound literal:

memcpy(data_input, (float []) {1.2, 2.4, 3.2, 4.5}, 4 * sizeof *data_input);

It's possible to use

float* data_input = malloc(4 * sizeof (float) );
memcpy( data_input, ( float [] ){1.2, 2.4, 3.2, 4.5 }, sizeof( float[4] ) );

But it has a drawback. Code duplication. Instead, you can do this:

float* data_input = malloc(4 * sizeof *data_input);
float tmp[] = { 1.2, 2.4, 3.2, 4.5 };
memcpy( data_input, tmp , sizeof tmp );

Or even

float tmp[] = { 1.2, 2.4, 3.2, 4.5 };
size_t size = sizeof tmp/sizeof tmp[0];
float* data_input = malloc(size * sizeof *data_input);
memcpy( data_input, tmp , sizeof tmp );

Note that the change from sizeof (float) to sizeof *data_input also is to avoid duplication.

Related