Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding offset of a structure element in c

Tags:

c

struct

struct a {     struct b     {         int i;         float j;     }x;     struct c     {         int k;           float l;     }y; }z; 

Can anybody explain me how to find the offset of int k so that we can find the address of int i?

like image 211
MSB Avatar asked Sep 11 '13 19:09

MSB


People also ask

What is offset value in C?

Description. The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.

What does offsetof do?

The offsetof() macro returns the offset of the element name within the struct or union composite. This provides a portable method to determine the offset. At this point, your eyes start to glaze over, and you move on to something that's more understandable and useful.


1 Answers

Use offsetof() to find the offset from the start of z or from the start of x.

offsetof() - offset of a structure member

SYNOPSIS

   #include <stddef.h>     size_t offsetof(type, member); 

offsetof() returns the offset of the field member from the start of the structure type.

EXAMPLE

   #include <stddef.h>    #include <stdio.h>    #include <stdlib.h>     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));         exit(EXIT_SUCCESS);    } 

You will get the following output on a Linux, if you compile with GCC:

       offsets: i=0; c=4; d=8 a=16        sizeof(struct s)=16 
like image 138
Gangadhar Avatar answered Oct 13 '22 23:10

Gangadhar