I have a struct meta
, one of which I insert at the start of my malloc:
void *ptr = malloc(sizeof(meta) + sz);
struct meta meta1;
meta1.size = sz;
//Which is better?
//memmove(ptr, &meta, sizeof(meta));
//ptr = meta;
Later on, I want to access my meta struct. I have tried doing:
*((struct meta*) (ptr - sizeof(m61_meta))).size;
Which, moves back the address to the 'start' of the malloc, casts the pointer to be a meta pointer, then gets size. However, I'm having a compile time error, saying that it is not a struct.
Why am I receiving this error, and if you know of a better way of doing this, that would be great.
EDIT: I am trying to put 'metadata' in my pointers. So basically:
memory
[meta|data]
A B
Where memory is just one malloc. I keep the pointer of data (B) and later on, I try and access the 'meta' of my data. That is,
(ptr - sizeof(m61_meta))
Which is the start of my memory
block. I want to access my meta from here. Unfortunately, casting my A
pointer to a struct meta
pointer fails.
The reason you're getting the compiler error is that the .
operator binds more tightly than the *
operator, so when you write
*((struct meta*) (ptr - sizeof(m61_meta))).size;
You're trying to take the size
member of a pointer. You probably mean
(*((struct meta*) (ptr - sizeof(m61_meta)))).size;
After that, I have no clue what your code is trying to do, but we'll deal with one bug at a time. It's almost certainly a mistake to do ptr - sizeof(...
, because pointer arithmetic is already scaled by the size of what's pointed to, so you'll end up skipping over a whole bunch of structures, not just one. Second, you've allocated space for a structure, but not copied anything into it. I'm sure there are more problems.
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.