Is there a standard pointer size declaration?

前端 未结 4 1358
无人及你
无人及你 2021-01-20 17:03

I have struct with padding in char (oops, my bad). I would like to subtract a pointer size. Do you know a standard pointer size declaration, or a standard macro

4条回答
  •  被撕碎了的回忆
    2021-01-20 17:58

    If you are looking for a portable way to find the offset in bytes of a structure member then you want to use the offsetof() macro defined in stddef.h:

    #include 
    #include 
    
    int main(void)
    {
        struct s {
            int i;
            char c;
            double d;
            char a[];
        };
    
        /* Output is compiler dependent */
    
        printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
                (long) offsetof(struct s, i),
                (long) offsetof(struct s, c),
                (long) offsetof(struct s, d),
                (long) offsetof(struct s, a));
        printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));
    
        return 0;
    }
    

    Output

    $ ./a.out
    offsets: i=0; c=4; d=8 a=16
    sizeof(struct s)=16
    

提交回复
热议问题