Thread: Using Offset in C

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    103

    Using Offset in C

    Hi All

    I am trying to understand offset in C and create it to print out the members reside on memory location using offset.

    I have written following code:

    Code:
    #include<stdio.h>
    #include<conio.h>
    
    typedef struct
    {
    	char name[10];
    	int age;
    	char address[100];
    } record;
    
    int main()
    {
       record rec,*ptr,p;
       int offset = 0;
       memset(&rec,0x00,sizeof(rec));
       memcpy(rec.name,"NICKMAN",7);
       memcpy(rec.address,"13 ALMOND STREET",20);
       rec.age = 17;
       ptr = &rec;
    
       offset = (char *)rec.name - (char *)ptr; 
       
       return 1;
    
    
    }
    
    Is this the correct way of creating offset?
    
    Also, how can I print the members using it.
    
    Can any body me further from here?
    
    Thanks
    Nickman

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Use the offsetof macro:
    Code:
    #include <stddef.h>
    ...
    printf("offset of address is %zu\n", offsetof(record, address));
    
    return 0;
    Remember to #include <stddef.h> so you can use the macro. The "%zu" is for printing size_t types, which is what offsetof returns. Returning 1 from main usually designates some sort of error in your program. You should return 0 or EXIT_SUCCESS.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Offset
    By N3utral in forum C++ Programming
    Replies: 0
    Last Post: 03-23-2010, 10:53 AM
  2. help! (int*)+offset
    By RobotGymnast in forum C++ Programming
    Replies: 6
    Last Post: 01-06-2008, 01:12 PM
  3. offset
    By Rhidian in forum C Programming
    Replies: 6
    Last Post: 04-14-2005, 08:57 AM
  4. What exactly is an 'offset' to something?
    By Shadow12345 in forum C++ Programming
    Replies: 4
    Last Post: 11-08-2002, 10:28 PM
  5. File offset
    By GaPe in forum C Programming
    Replies: 7
    Last Post: 12-29-2001, 04:56 PM