简体   繁体   中英

How to type cast a struct into allocated char memory space

I am trying to use the first few bytes of a section of memory on the heap to store meta-data about the section memory using C language (not C++).

The heap space is created using:

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

Now, I'm trying to place a 'meta' struct in the first 4 bytes of allocated heap space.

typedef struct{
    int test;
}meta_t;

This is a test code I'm using to just understand how to do it before I implement it in the larger code.

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;
}

Side note: Why does this type cast work:

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

but this type cast doesn't?:

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

The main question is how can I fit the 'meta' data type (4 bytes) in to four char sized (1 byte) spaces at the start of the start_mem?

FYI - This is a small part of a larger project in a data structures class. Having said that there is no need to reply with "Why would you even bother to do this?" or "You could just use function_abc() and do the same thing." Restrictions have been set (ie a single use of malloc() ) and I would like to follow them.

You could use 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;
}

What about this one?

memcpy(start_mem, &meta, sizeof meta);

Note that you have to pay attention to endianness .

Even more simple, do a typecasted assignment:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM