我正在编写一个函数,其中我需要多次调用Malloc来动态地为非常小的数组(如4-5个整数)分配内存.组合和长度在运行时确定).这些数组用于存储不同类型的数据类型.因此,我想要分配一个大内存,并将其用于所有类型.这就是我想要做的.
#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;
}
我现在很困惑,这是一种允许的好做法吗?