Thread: Pointer Size Relative To Integers?

  1. #1
    Registered /usr
    Join Date
    Aug 2001
    Newport, South Wales, UK

    Pointer Size Relative To Integers?


    I've just wandered into a situation whereby I'm attempting to traverse a struct in memory that I know nothing about bar its size in bytes and that it ends with a pointer to another struct. In order to get to this other struct, I'm doing:-
    // pretend that we know that structure is good and size truthful...
    void *getstruct(void *structure, size_t size)
        return (void *)*(unsigned long *)((unsigned char *)structure + size - sizeof(void *));
    The thing is, I had to cast to an unsigned long pointer to get the address, not being able to dereference a void pointer. But I haven't seen anything that says that a pointer is always the same size as a long, plus I think that I may also run into alignment errors.

    Is there a better way to do this?

  2. #2
    Registered User
    Join Date
    Jun 2005
    No relationship is guaranteed between the size of a void pointer and the size of a long.

    All you need to do is get the address that is stored at the end of your struct: that will be the address of the next one.
         return (void *)((char *)structure + size - sizeof(void *));

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 04-04-2009, 03:45 AM
  2. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  3. size of a pointer
    By anykey in forum C++ Programming
    Replies: 3
    Last Post: 05-04-2005, 11:16 AM
  4. size of the memory reserved for a pointer
    By cris_orpi in forum C Programming
    Replies: 13
    Last Post: 03-05-2003, 11:42 AM
  5. size of a char pointer (*)
    By Garfield in forum C Programming
    Replies: 14
    Last Post: 10-04-2001, 07:00 PM