Finding offset of a structure element in c

c offsetof
c get offset of struct member
c get offset of field in struct
__builtin_offsetof
c structure offsetof
gdb offsetof
offsetof union
offsetof gcc
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?

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

Neat hack to find offsets of C Structure members, Applying & on the structure element (in this case it is c) returns the Please write comments if you find anything incorrect, or you want to share� 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.

It's been 3 years since the question has been asked, I'm adding my answer for the sake of completeness.

The hacky way of getting the offset of a struct member goes like this

printf("%p\n", (void*)(&((struct s *)NULL)->i));

It doesn't look pretty, I can't think of anything in pure C (which can get you the offset of the member, without knowing anything else about the structure. I believe the offsetof macro is defined in this fashion.

For reference, this technique is used in the linux kernel, check out the container_of macro :

http://lxr.free-electrons.com/source/scripts/kconfig/list.h#L18

A more elaborate explanation can be found in this article:

http://radek.io/2012/11/10/magical-container_of-macro/

The OFFSETOF() macro, For help finding or replacing the problematic tags, see instructions. (February 2019). C's offsetof() macro is an ANSI C library feature found in stddef.h. It evaluates to the offset (in bytes) of a given member within a struct or union NULL) { struct my_struct *element = container_of(current, struct my_struct, list); printf("%s\n",� name offset = 0 byte in address structure. street offset = 50 byte in address structure. phone offset = 100 byte in address structure. stddef_h.htm Previous Page Print Page

struct a foo;
printf("offset of k is %d\n", (char *)&foo.y.k - (char *)&foo);    
printf("offset of i is %d\n", (char *)&foo.x.i - (char *)&foo);

foo.x.i refers to the field i in the struct x in the struct foo. &foo.x.i gives you the address of the field foo.x.i. Similarly, &foo.y.k gives you the address of foo.y.k; &foo gives you the address of the struct foo.

Subtracting the address of foo from the address of foo.x.i gives you the offset from foo to foo.x.i.

As Gangadhar says, you can use the offsetof() macro rather than the pointer arithmetic I gave. But it's good to understand the pointer arithmetic first.

offsetof, This macro with functional form returns the offset value in bytes of member member in the data structure or union type type. The value returned is an unsigned� Applying & on the structure element (in this case it is c) returns the address of the element which is 0x10. Casting the address to unsigned int (size_t) results in number of bytes the element is placed in the structure. Note: We may consider the address operator & is redundant. Without address operator in macro, the code de-references the

As already suggested, you should use the offsetof() macro from <stddef.h>, which yields the offset as a size_t value.

For example:

#include <stddef.h>
#include <stdio.h>
#include "struct_a.h"  /* Header defining the structure in the question */

int main(void)
{
    size_t off_k_y = offsetof(struct c, k);
    size_t off_k_z = offsetof(struct a, y.k);
    size_t off_i_x = offsetof(struct b, i);
    size_t off_i_z = offsetof(struct a, x.i);

    printf("k = %zu %zu; i = %zu %zu\n", off_k_y, off_k_z, off_i_x, off_i_z);
    return 0;
}

Example output:

k = 0 8; i = 0 0

offsetof - C++ Reference, The offsetof() macro returns the offset of the element name within the field b.h resides in the structure, then the simplest way to find out is to� The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared. Following is the declaration for strstr() function. This function returns a pointer to

Here's a generic solution:

#if defined(__GNUC__) && defined(__GNUC_MINOR__)
#  define GNUC_PREREQ(minMajor, minMinor) \
         ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((minMajor) << 16) + (minMinor))
#else
#  define GNUC_PREREQ 0
#endif

#if GNUC_PREREQ(4, 0)
#  define OFFSETOF(type, member) ((int)__builtin_offsetof(type, member))
#else
#  define OFFSETOF(type, member) ((int)(intptr_t)&(((type *)(void*)0)->member) )
#endif

How to Use C's offsetof() Macro, The macro offsetof() returns the offset of the field member from the start of the structure type. Consequently, an element's offset is not necessarily given by the sum of the sizes of the a.out offsets: i=0; c=4; d=8 a=16 sizeof(struct s)=16. C Structures. Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only.

offsetof(3): offset of structure member, Let's say we have the following structure: struct { int a; char c; } example; To calculate offset of 'c', we have following ways: 1. Use the macro� Before you proceed this section, we recommend you to check C dynamic memory allocation. Sometimes, the number of struct variables you declared may be insufficient. You may need to allocate memory during run-time. Here's how you can achieve this in C programming. Example: Dynamic memory allocation of structs

C Structures: Calculating offset of an element – Simplify Complexities, Furthermore, if you consult the compiler manuals, you'll find an “The offsetof() macro returns the offset of the element name within the In a nutshell, if the structure name you use, call it s , results in a valid C expression� This macro with functional form returns the offset value in bytes of member member in the data structure or union type type. The value returned is an unsigned integral value of type size_t with the number of bytes between the specified member and the beginning of its structure. Parameters type A type in which member is a valid member designator.

Learn a new trick with the offsetof() macro, I have a structure I would like to compute the offset to members within. Actually, ANSI C has a macro for that. structure to make it more comfortable to work with. if so, adding up elements size might leave your program Well it is rather simple (surprisingly) and the reason I asked was I could not find offsetof() macro (sad). Structure within structure (nested structure in C ) using pointer variable: This program explains how to use structure within structure in C using pointer variable. “student_college_detail’ structure is declared inside “student_detail” structure in this program. one normal structure variable and one pointer structure variable is used in this program.

Comments
  • It's layed out as so [ sizeof(int), sizeof(float), sizeof(int), sizeof(float) ]
  • You can find the offset of k from the start of y, or from the start of z; you can find the offset of i from the start of x or from the start of z. However, there is essentially no guaranteed way to find the offset of k given the offset of i. You can make non-portable assumptions to come up with an answer, but why would you do that when you can come up with a portable method that doesn't involve assumptions.
  • @koodawg Not necessary. It depends on the compiler and target architecture. Sometimes the compiler may add padding to ensure that fields find the addresses with the desired alignment. software.intel.com/en-us/blogs/2011/08/18/…
  • -1 : The question specifically requests how to find the offset of an element in a nested struct ...This post does not answer that question.
  • @BlueChip Sure it does, you just need to take advantage of the power of your human mind. offsetof(struct a, y) + offsetof(struct c, k) works just fine.
  • Could you please clarify how &((struct s *)NULL)->i would work fine but ((struct s *)NULL)->i gives segmentation fault
  • @Karthik The -> operator has higher precedence than the & operator. Thus &((struct s *)NULL)->i is equivalent to &(((struct s *)NULL)->i), which is like saying take address of (((struct s *)NULL)->i).
  • @Silen, why we are adding NULL in &((struct s *)NULL)->i?
  • Try it, see what you get. Probably 0 for i, and 8 for k. See Nick's comment above.
  • Maybe foo.x.i refers to the field i in the struct x in the struct foo (x vs. y).
  • The OP seems to be looking for the address of i, so seems to me you can stop at &foo.x.i.