如何将结构类型转换为分配的 char 内存 space

How to type cast a struct into allocated char memory space

我正在尝试使用堆上一段内存的前几个字节来使用 C 语言(而不是 C++)存储有关该段内存的元数据。

堆 space 是使用以下方法创建的:

char* start_mem = (char*)malloc(10*sizeof(char)); //10 bytes of memory

现在,我试图在分配的堆 space 的前 4 个字节中放置一个 'meta' 结构。

typedef struct{
    int test;
}meta_t;

这是一个测试代码,我用它来了解如何在更大的代码中实现它之前。

test #include <stdio.h>

typedef struct{
    int test;
} meta_t;

int main(void) {

    char* start_mem = (char*)malloc(10*sizeof(char));

    meta_t meta;
    meta.test = 123;

    return 0;
}

旁注:为什么这种类型转换有效:

int test = 123;
char c = (char) test;

但是这种类型转换没有?:

meta_t meta;
meta.test = 123;
char c = (char) meta;

主要问题是如何将 'meta' 数据类型(4 字节)放入 start_mem 开头的四个字符大小(1 字节)spaces ?

仅供参考 - 这是数据结构中较大项目的一小部分 class。话虽如此,但无需回复 "Why would you even bother to do this?" 或 "You could just use function_abc() and do the same thing." 已设置限制(即一次使用 malloc() ),我想遵循它们。

你可以使用 memcpy:

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

typedef struct{
    int test;
} meta_t;

int main() {

    char *start_mem = malloc(10);

    meta_t meta;
    meta.test = 123;

    memcpy(start_mem, &meta, sizeof(meta));

    printf("Saved: %d\n", ((meta_t *)(start_mem))->test);

    return 0;
}

这个怎么样?

memcpy(start_mem, &meta, sizeof meta);

注意要注意endianness.

更简单,做一个类型转换赋值:

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

typedef struct{
  int test;
} meta_t;

int main() {

  char *start_mem = malloc(10);

  meta_t meta;
  meta_t *p;
  meta.test = 123;

  p = (meta_t *) start_mem;
  *p = meta;

  printf("Saved: %d\n", ((meta_t *)(start_mem))->test);

  return 0;
}