Kavya <> wrote:
> Here is the code
> int main(){
> struct node{
> int a;
> int b;
> int c;
> };
> struct node s={3,5,6};
> struct node *ptr=&s;
> printf("%d",*(int*)ptr);
> }
> Will the last printf always result in correct output? Is it safer to
> access data members of structure this way?
You are guaranteed that address of the first element of a structure
is always at the address of the structure, so you can safely access
the member 'a' of your structure that way (if it's a good idea is
a totally different question). For the other members it's not safe,
e.g.
printf( "%d", * (int *) ((char *) ptr + sizeof(int)));
is _not_ guranteed to print out the value you stored in the member
'b' since the compiler is allowed to insert as many padding bytes
between the structure members as it likes.
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://toerring.de