Re: Does *&s1 refer to the first member of structure variable s1



lovecreatesbea...@xxxxxxxxx wrote On 07/05/07 10:24,:
Does the expression *(int *)&s1 below inside the printf() statement
guarantee to refer to the first member of the structure variable s1?
I've tried the code and it seems that it works that way. The C
standard states this? Thank you very much.

#include <stdio.h>

struct S{
int m1, m2, m3;
};

int main(void)
{
struct S s1 = {3, 4, 5};
printf("%d\n", *(int *)&s1);
return 0;
}

Yes. A pointer to a struct can be converted to a
pointer to the struct's first element (if it is possible
to make such a pointer at all), and vice versa.

This guarantee applies only to the *first* element,
not to any subsequent elements. In your sample, it is
*not* guaranteed that (int*)&s1+1 == &s1.m2.

--
Eric.Sosman@xxxxxxx
.



Relevant Pages

  • Re: Memory Structure Pointer Problems
    ... typedef struct sta { ... char* name; ... int num_cmpnds; ... A pointer to a struct cmp is almost ...
    (comp.lang.c)
  • Re: Another spinoza challenge
    ... You should test against the int type's limits: ... typedef struct complex ... a pointer to an integer ... A macro is preferable because it is replaced by inline code, ...
    (comp.lang.c)
  • Re: Another spinoza challenge
    ... int main{ ... using struct and typedef. ... a pointer to an integer ... A macro is preferable because it is replaced by inline code, ...
    (comp.lang.c)
  • Re: [RFC][PATCH 1/6] memcg: fix pre_destory handler
    ... returns struct cgroup of id. ... SwapCgroup uses array of "pointer" to record the owner of swaps. ... struct cgroup_id is freed by RCU. ... changed interface from pointer to "int" ...
    (Linux-Kernel)
  • gcc, aliasing rules and unions
    ... struct B {int x, y;}; ... A struct pointer can be converted to another ... Also I don't know what the "effective type" of a union member is. ...
    (comp.lang.c)