首页 文章

如何键入将结构转换为已分配的char内存空间

提问于
浏览
0

我试图使用堆上一段内存的前几个字节来存储使用C语言(而不是C)的段内存的元数据 .

使用以下内容创建堆空间:

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

现在,我试图在分配的堆空间的前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;

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

仅供参考 - 这是数据结构类中较大项目的一小部分 . 话虽如此,没有必要回答“你为什么还要费心去做?”或者“你可以使用function_abc()并做同样的事情 . ”已经设置了限制(即单次使用malloc()),我想跟随它们 .

3 回答

  • 0

    这个如何?

    memcpy(start_mem, &meta, sizeof meta);
    

    请注意,您必须注意 endianness .

  • 0

    你可以使用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;
    }
    
  • 0

    你(们)能做到 :

    *((meta_t *)start_mem) = meta;
    

    (你的行为就像start_mem是一个meta_t);要么

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

    阅读时更干净 .

相关问题