RicardasSim icon

struct, offset

RicardasSim | PRO | 01/28/20 03:12:12 PM UTC | 0 ⭐ | 680 👁️ | Never ⏰ | []
C |

2.1 KB

|

None

|

0 👍

/

0 👎

//-std=c99 -Wall -Wextra -Wpedantic -Wshadow
//gcc 64bit
 
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
 
int main()
{
 
    typedef float vec2[2];
    typedef float vec3[3];
    typedef float vec4[4];
 
    struct st{
        char a;
        int b;
        float c;
        double d;
        vec2 v2;
        vec3 v3;
        vec4 v4;
    };
 
 
    struct st s;
 
    struct st *ps;
 
    printf ("sizeof struct st: %zu\n", sizeof (struct st) );
    printf ("sizeof s: %zu\n", sizeof s );
    printf ("sizeof &s: %zu\n", sizeof &s );
    printf ("sizeof ps: %zu\n", sizeof ps );
    printf ("sizeof *ps: %zu\n", sizeof *ps );
 
    ps = malloc ( sizeof(struct st) );
 
    if ( !ps )
    {
        printf("memory allocation error.\n");
        return 1;
    }
 
    ps->a = 1;
 
    printf("(1) %d\n", ps->a);
 
    (*ps).a = 2;
 
    printf("(2) %d\n", ps->a);
 
    printf ("address of s: %p\n", (void*) &s );
    printf ("address of ps: %p\n", (void*) ps );
 
    printf( "offsetof  b: %ld\n", offsetof( struct st, b) );
    printf( "offsetof v3: %ld\n", offsetof( struct st, v3) );
    printf( "offsetof v4: %ld\n", offsetof( struct st, v4) );
    printf ("between v3 and v4: %ld\n", offsetof( struct st, v4) - offsetof( struct st, v3) );
 
    printf ("sizeof ps->a: %zu\n", sizeof ps->a );
 
    printf ("address of ps->a: %p\n", (void*) &ps->a );
    printf ("address of ps->b: %p\n", (void*) &ps->b );
 
    long offset = (char*) &ps->b - (char*) ps;
    printf ("offset of ps->b: %ld\n", offset );
 
    offset = (char*) &ps->v4 - (char*) &ps->v3;
    printf ("between v3 and v4: %ld\n", offset );
 
    free(ps);
 
    return 0;
}
 
/*
output:
 
sizeof struct st: 64
sizeof s: 64
sizeof &s: 8
sizeof ps: 8
sizeof *ps: 64
(1) 1
(2) 2
address of s: 0x7ffdbef19500
address of ps: 0x558174b85670
offsetof  b: 4
offsetof v3: 32
offsetof v4: 44
between v3 and v4: 12
sizeof ps->a: 1
address of ps->a: 0x558174b85670
address of ps->b: 0x558174b85674
offset of ps->b: 4  // 4 because of alignment, https://pastebin.com/kEdeRr5b
between v3 and v4: 12
 
*/

Comments