Take the following example:
typedef struct array_struct {
unsigned char* pointer;
size_t length;
} array;
typedef struct vector_struct {
unsigned char* pointer;
// Reserved is the amount of allocated memory not being used.
// MemoryLength = length + reserved;
size_t length, reserved;
} vector;
// Example Usage:
vector* vct = (vector*) calloc(sizeof(vector), 1);
vct->reserved = 0;
vct->length = 24;
vct->pointer = (unsigned char*) calloc(arr->length, 1);
array* arr = (array*) vct;
printf("%i", arr->length);
free(arr->pointer);
free(arr);
C seems to allocate memory for struct members in the order they're defined in the struct. Which means that if you cast vector -> array
you'll still get the same results if you perform operations on array
as you would as if you did it on vector
since they have the same members and order of members.
As long as you only down cast from vector -> array
as if array
was a generic type for vector
you shouldn't run into any problems.
Is this undefined and bad behavior despite the similar structure of the types?