RicardasSim

struct, offset

Jan 28th, 2020
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.10 KB | None | 0 0
  1. //-std=c99 -Wall -Wextra -Wpedantic -Wshadow
  2. //gcc 64bit
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stddef.h>
  7.  
  8. int main()
  9. {
  10.  
  11.     typedef float vec2[2];
  12.     typedef float vec3[3];
  13.     typedef float vec4[4];
  14.  
  15.     struct st{
  16.         char a;
  17.         int b;
  18.         float c;
  19.         double d;
  20.         vec2 v2;
  21.         vec3 v3;
  22.         vec4 v4;
  23.     };
  24.  
  25.  
  26.     struct st s;
  27.  
  28.     struct st *ps;
  29.  
  30.     printf ("sizeof struct st: %zu\n", sizeof (struct st) );
  31.     printf ("sizeof s: %zu\n", sizeof s );
  32.     printf ("sizeof &s: %zu\n", sizeof &s );
  33.     printf ("sizeof ps: %zu\n", sizeof ps );
  34.     printf ("sizeof *ps: %zu\n", sizeof *ps );
  35.  
  36.     ps = malloc ( sizeof(struct st) );
  37.  
  38.     if ( !ps )
  39.     {
  40.         printf("memory allocation error.\n");
  41.         return 1;
  42.     }
  43.  
  44.     ps->a = 1;
  45.  
  46.     printf("(1) %d\n", ps->a);
  47.  
  48.     (*ps).a = 2;
  49.  
  50.     printf("(2) %d\n", ps->a);
  51.  
  52.     printf ("address of s: %p\n", (void*) &s );
  53.     printf ("address of ps: %p\n", (void*) ps );
  54.  
  55.     printf( "offsetof  b: %ld\n", offsetof( struct st, b) );
  56.     printf( "offsetof v3: %ld\n", offsetof( struct st, v3) );
  57.     printf( "offsetof v4: %ld\n", offsetof( struct st, v4) );
  58.     printf ("between v3 and v4: %ld\n", offsetof( struct st, v4) - offsetof( struct st, v3) );
  59.  
  60.     printf ("sizeof ps->a: %zu\n", sizeof ps->a );
  61.  
  62.     printf ("address of ps->a: %p\n", (void*) &ps->a );
  63.     printf ("address of ps->b: %p\n", (void*) &ps->b );
  64.  
  65.     long offset = (char*) &ps->b - (char*) ps;
  66.     printf ("offset of ps->b: %ld\n", offset );
  67.  
  68.     offset = (char*) &ps->v4 - (char*) &ps->v3;
  69.     printf ("between v3 and v4: %ld\n", offset );
  70.  
  71.     free(ps);
  72.  
  73.     return 0;
  74. }
  75.  
  76. /*
  77. output:
  78.  
  79. sizeof struct st: 64
  80. sizeof s: 64
  81. sizeof &s: 8
  82. sizeof ps: 8
  83. sizeof *ps: 64
  84. (1) 1
  85. (2) 2
  86. address of s: 0x7ffdbef19500
  87. address of ps: 0x558174b85670
  88. offsetof  b: 4
  89. offsetof v3: 32
  90. offsetof v4: 44
  91. between v3 and v4: 12
  92. sizeof ps->a: 1
  93. address of ps->a: 0x558174b85670
  94. address of ps->b: 0x558174b85674
  95. offset of ps->b: 4  // 4 because of alignment, https://pastebin.com/kEdeRr5b
  96. between v3 and v4: 12
  97.  
  98. */
Advertisement
Add Comment
Please, Sign In to add comment