C Language | Structure Declarations | Converting Structure Types
You cannot directly convert one structure value into another structure type. You can, however, convert pointers to structures when their memory layouts are compatible.
Casting Structure Pointers
Different structure types cannot be assigned or cast directly.
struct Point pt = { 10 , 100 };
struct Size sz = pt; /* compilation error */
Consider structures with the same physical layout:
struct Point { int x , y; };
struct Size { int width , height; };
Although the member names and meanings differ, both structures contain two int members. A pointer cast can reinterpret the same memory with the other layout.
Code 1
#include <stdio.h>
struct Point { int x , y; };
struct Size { int width , height; };
int main() {
struct Point pt = { 400 , 300 };
struct Size *psz = (struct Size *)&pt;
printf("&pt.x = %p : pt.y = %p\n" , &pt.x , &pt.y);
printf("&psz->width = %p , &psz->height = %p\n" , &psz->width , &psz->height);
printf("psz->width = %d : psz->height = %d\n" , psz->width , psz->height);
return 0;
}
This technique requires care. Incorrect assumptions about layout, alignment, or compatibility can cause bugs and make debugging difficult.
Compatible prefixes can also support limited extension of an existing structure.
Code 2
#include <stdio.h>
struct Color { char *name; int r , g , b; };
struct ColorEx { char *name; int r , g , b , a; };
void SetColor(struct Color *color) {
printf("%s r = %d : g = %d : b = %d\n" ,
color->name , color->r , color->g , color->b);
}
int main() {
struct Color color = { "Color" , 0xFF , 0 , 0 };
struct ColorEx colorEx = { "ColorEx" , 0 , 0xFF , 0 , 0xA0 };
SetColor(&color);
SetColor((struct Color *)&colorEx);
return 0;
}
ColorEx declares name, r, g, and b in the same order as Color, then adds a. Existing functions that only read the compatible prefix can accept a cast pointer. More flexible APIs may use void *, and extensible designs often store the structure size in a member so that callers can identify supported fields.