Adding integral bytes to foo pointers

George Williams gww%aphasia.uucp at BRL.ARPA
Mon Sep 9 06:55:29 AEST 1985


> >Since 'p+n', where p is a pointer and n is an integer, is equivalent to
> >adding n*sizeof(whatever p points to), the safe and portable way of adding
> >an integer to a pointer treated as an integer is
> >	 (char *)p + n
>
> This will break down on machines which are bit or word oriented, rather than
> byte oriented.  The real question is why do you need to do this in the first
> place?

I can give one reason as to why this is desirable: Suppose one wants to
implement the PL/I area construct in c (For those who don't know PL/I
the area type defines a large space into which other types can be put,
and then encourages the use of offsets rather than pointers.  This is
very useful if you want to be able to save a symbol table (or some such)
on disk in one program, and then read it in in another without having to
chase down and fixing up pointers).

I have an application where I want to be able to save masses of objects
most with lots of pointers in them to other objects, and then use this
result to initialize the program the next time it runs.  Obviously I don't
want to do much processing when I initialize.  So what I have done is not
to store pointers, but to store offsets from the base of the current object;
thus if I save the appropriate part of memory (with no processing) and then
read it in to a different part of memory (again no processing) I have valid
offsets.

Now I need some standard form to store my offsets in, I can't use
sizeof(current object) because not all objects are the same type, and even
if they were I can't guarantee that they will be aligned properly (how much
overhead does malloc use on your machine?). So I use byte offsets, and when-
ever I want what an offset points to I have to do something like this:
    next = (ENTRY *) (((char *) ent) + ent->sym_next);
I know this will cause problems (or at least be slow) on things like dec10s
and dgs, but I can't think of a better way.

Does anyone have a better way of saving large chunks of processed data?

			    George Williams
			    decvax!cit-vax!aphasia!gww


You must come to know me; not so much now, because now
I'm excited, but I have got at least three virtues.
How many have you got?



More information about the Comp.lang.c mailing list