I am writing a function where I need to call malloc multiple times to allocate memory for very small arrays dynamically (like 4-5 ints. The combinations and lengths are determined during runtime). These arrays are used to store different types of datatypes. so I thought of allocating a large memory and use it for all types. Here is what I am trying to.
#include <stdio.h>
#include <stdlib.h>
int main() {
size_t n_char = 4, n_float =4 ; /* these are not fixed.
I set this just for demonstrative purposes,
n_char and n_float value are determined
during runtime */
char * a = malloc( n_char*sizeof(char) + n_float*sizeof(float) ); /* Allocating for 4 ints and 4 chars*/
for (int i=0; i<4 ; ++i) a[i] = 'a' ;
float *b = (void *)(a+4) ; /* can we cast this pointer in this way ?*/
for (int i=0; i<4 ; ++i) b[i] = 1.0f ;
for (int i=0; i<4 ; ++i) printf("%c" , a[i]) ;
printf("\n");
for (int i=0; i<4 ; ++i) printf("%f " , (double)b[i]) ;
printf("\n");
return 0;
}
I am now confused, is this a good allowed practice ?