J
Jonathan Lee
Hello all,
I've have a variation of the struct hack that I think is legal. Wondering if anyone could spot a reason why not. (By struct hack I mean putting a variable length array at the end of a struct, or a struct at the beginning of an array).
Suppose I want to add an int array to the end of
struct header
{
int a;
int b;
double c;
// int arr[]; // I think C99 would do this
}
Then I can make the union
union wrap
{
header hdr;
int arr[1];
}
And use calloc to get some memory
void* p = calloc(20, sizeof(wrap));
The following casts should be legal:
union* u = static_cast<union*>(p);
header* h = static_cast<header*>(u);
int* i = static_cast<int*>(u);
But, then, this should also be legal
int* j = static_cast<int*>(u + 1);
which is an aligned int pointer just past the header
struct. Seeing as how this came from calloc-d, "void"
memory, I think j + 0, j + 1, j + 2, ... are legal
int addresses.
After all, I can legally use
int* q = static_cast<int*>(p);
as an int array. I don't see why j would be any
different.
Can anyone see why this wouldn't be the case?
Thanks in advance,
--Jonathan
I've have a variation of the struct hack that I think is legal. Wondering if anyone could spot a reason why not. (By struct hack I mean putting a variable length array at the end of a struct, or a struct at the beginning of an array).
Suppose I want to add an int array to the end of
struct header
{
int a;
int b;
double c;
// int arr[]; // I think C99 would do this
}
Then I can make the union
union wrap
{
header hdr;
int arr[1];
}
And use calloc to get some memory
void* p = calloc(20, sizeof(wrap));
The following casts should be legal:
union* u = static_cast<union*>(p);
header* h = static_cast<header*>(u);
int* i = static_cast<int*>(u);
But, then, this should also be legal
int* j = static_cast<int*>(u + 1);
which is an aligned int pointer just past the header
struct. Seeing as how this came from calloc-d, "void"
memory, I think j + 0, j + 1, j + 2, ... are legal
int addresses.
After all, I can legally use
int* q = static_cast<int*>(p);
as an int array. I don't see why j would be any
different.
Can anyone see why this wouldn't be the case?
Thanks in advance,
--Jonathan