Thread: c offsetof macro. quick question

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    35

    c offsetof macro. quick question

    I'm screwing around with the macro offsetof. Just for the sake of screwing around with it. I can't figure out one piece. Here's my code:

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <stddef.h>
    
    struct Object {
    	int rc;
    };
    
    struct RawPoint {
    	int x,y;
    };
    
    struct Point {
    	struct Object _;
    	int x;
    	int y;
    };
    
    int main(int argc, char ** argv) {
    	struct Point * point = malloc(sizeof(struct Point));
    	point->x = 10;
    	point->y = 10;
    	size_t offset = offsetof(struct Point,x);
    	
    	struct RawPoint * rawPoint = (struct RawPoint *) (point + offset);
    	struct RawPoint * rawPoint2 = (struct RawPoint *) &(point->x);
    	
    	//shouldn't rawPoint and rawPoint2 be the same address?
    	
    	printf("offset: %ld\n",(long)offset);
    	printf("point: %p\n",point);
    	printf("rawPoint: %p\n",rawPoint);
    	printf("rawPoint2 %p\n",rawPoint2);
    	
    	
    	return 0;
    }
    I'm trying to figure out why rawPoint and rawPoint2 aren't the same addresses? I'm obviously missing something. Any ideas?

    Thanks!

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Remember how pointer arithmetic works. "ptr + n" adds n*sizeof(*ptr) to the address, not just n bytes.

    When navigating bytewise in memory, everything needs to be cast to char *
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Jul 2009
    Posts
    35
    Quote Originally Posted by brewbuck View Post
    Remember how pointer arithmetic works. "ptr + n" adds n*sizeof(*ptr) to the address, not just n bytes.

    When navigating bytewise in memory, everything needs to be cast to char *
    doh! thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. very quick question.
    By Unregistered in forum C++ Programming
    Replies: 7
    Last Post: 07-24-2002, 03:48 AM
  2. quick question
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 07-22-2002, 04:44 AM
  3. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 11:04 AM
  4. Quick Question on File Names and Directories
    By Kyoto Oshiro in forum C++ Programming
    Replies: 4
    Last Post: 03-29-2002, 02:54 AM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 05:46 PM