如何将不同类型存储到 C 中分配的内存中?

How to store different types to allocated memory in C?

我需要分配 5 个字节的内存。我喜欢这样做:

uint16_t* memory = (uint16_t*) malloc(5);

我的问题是如何将不同的类型存储到该内存中并进行打印。具体来说,我需要 3x char、1x float 和 1x int。

如果没有关于作业的更广泛的上下文,则无法确定您的导师正在寻找的解决方案,但要清楚 malloc() returns 指向内存的空指针保证在可以解释为任何基本类型的方式。

这里使用 uint16_t 似乎相当随意,大概是为了测试您对指针概念和类型转换的了解而选择的。 5 字节长度的奇怪选择也可能是为了强调 space 只需要足够大以容纳要存储的最大对象这一事实。

这似乎是学校作业中最受欢迎的任务之一,但不一定鼓励良好的编码实践。也就是说,可能需要以下 'dirty' 解决方案:

uint16_t* memory = (uint16_t*) malloc(5);

char* c = (char*)memory ;
c[0] = 'a' ;
c[1] = 'b' ;
c[2] = 'c' ;

float* f = (float*)memory ;
*f = 1.0 ;

int* i = (int*)memory ;
*i = 123 ;

一个更复杂的解决方案,可能会超出您的范围 material 是使用联合:

union
{
    uint16_t s ;
    char c[3] ;
    float f ;
    int i ;
}* memory = malloc( sizeof( *memory ) ) ;

memory->c[0] = 'a' ;
memory->c[1] = 'b' ;
memory->c[2] = 'c' ;

memory->f = 1.23 ;

memory->i = 123 ;

如果特定的分配行是“必需的”,那么您可以使用命名联合并强制转换 memory:

uint16_t* memory = malloc(5);
union variant
{
    char c[3] ;
    float f ;
    int i ;
} ;

((union variant*)memory)->f = 1.23 ;

((union variant*)memory)->i = 123 ;

((union variant*)memory)->c[0] = 'a' ;
((union variant*)memory)->c[1] = 'b' ;
((union variant*)memory)->c[2] = 'c' ;