user1709076 user1709076 - 3 months ago 8
C Question

possible to set all elements of pointer to float after malloc

Is there anyway to do the following in C?

float *t = (float*)malloc(t_size*sizeof(float));
t = {
1,0,0,
-1,0,0,
0,1,0
};


Similar to how the following is standard

float t[9] = {
1,0,0,
-1,0,0,
0,1,0
};

LPs LPs
Answer

As asked, a soultion can be done using compound literals

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

int main()
{
    #define  t_size  9
    float *t = malloc(t_size*sizeof(*t));

    if (t != NULL)
    {
       memcpy(t, (float[t_size]){1,0,0,-1,0,0,0,1,0}, t_size*sizeof(*t));

       for (size_t i=0; i<t_size; i++)
          printf("t[%zu] = %g\n", i, t[i]);
    }

    free(t);

    return 0;
}
Comments