C language ensures that a pointer to any struct may be converted to void * and vice versa. Also, the language permits to define pointers to a struct also if it’s undefined. I would assume that, since the compiler doesn’t know anything about these structures, their pointers should have the same physical representation. Let’s consider these lines into two separate modules:
/* FILE1.c */
void *mem = ...; //Points to a suitable memory block
struct s1 *p1; //No implementation given for struct s1
void *mem2;
p1 = (struct s1 *)mem;
mem2 = &p1;
/* FILE2.c */
extern void *mem2;
struct s2 { /*...fields...*/ };
struct s2 *p2;
p2 = *(struct s2 **)mem2;
Is this code able to work on all the platforms, provided that the memory block is large enough to contain struct s2 (e.g. allocated by malloc(sizeof(struct s2)))?
In other words, is it correct (i.e. portable) to reinterpret a memory cell containing a pointer to struct s1 structure as if it were a pointer to struct s2?
(Disclaimer: I am perfectly aware that this is a very weird way to play with pointers, my question is theoretical)
In C, pointers are not required to have the same size or representation.
It means
sizeof (int *)can be different tosizeof (double *)for example.The only requirements are:
void *,char *,signed char *andunsigned char *have thesame representation.
Pointers to structures have the same representation.
Pointers to unions have the same representation.