3 ms·
Another question for language lawyers: if you are given a pointer to char, is it defined behavior to somehow cast the data before that into a correct integer?
by projektfu 7y ago
Another question for language lawyers: if you are given a pointer to char, is it defined behavior to somehow cast the data before that into a correct integer? Assuming you have
typedef struct MyStr {
size_t mystr_length;
char [1];
} MyStr;
typedef char *PMyStr;
size_t MyStrLen(const PMyStr p) {
const MyStr *pmystr = ?;
const size_t *psize_t = ?;
return *psize_t;
}
How do you make a legal cast to get either pmystr or psize_t?
- saagarjha 7y agoThat depends on what p points to. If it’s the address of the char[1] array inside a valid PMyStr, then as far as I’m aware you can subtract the correct number of bytes (offsetof is your friend) and cast the resulting pointer to your MyStr, then get the size from there.
- projektfu 7y agoAh, with your information I'm looking into the container_of macro which I'm not entirely certain is legitimate but hasn't run into problems.