[comp.lang.c] absolute variable positioning

jharkins@sagpd1.UUCP (Jim Harkins) (09/08/89)

Due to some hardware considerations I have a special block of memory that I
have to use for storage of some variables.  Lets say it starts at address FOO.
In C, whats the best way to say "integer fred in normal mem, struct wilma
somewhere after FOO, struct barney somewhere after FOO, struct bam_bam in
normal mem", etc?  The best I can come up with is

pointer = FOO
struct a *wilma = pointer
pointer += sizeof(struct a)
struct b *barney = pointer
pointer += sizeof(struct b) * NUMBER_OF_BARNEYS     /* array of barneys */

etc etc

Needless to say, this seems somewhat cumbersome and prone to error.  Especially
to the poor sucker that has to maintain the code.

To try to cut down on the number of well-meaning but frivolous responces:

1.  If I made a stupid mistake in this message, assume I know what I'm doing
    and I made a typo.  (I seem to get more responces from typos than anything).
2.  If I have to resort to the scheme above I'll encapsulate it in a function.
3.  So far I haven't needed to de-allocate variables once allocated, and they
    all get allocated on power up.  But this may change...
4.  I don't have a malloc available to do this unless I write one myself.
    (I know, one's in K&R).


                                                Jim
                                            "Only dead fish go with the flow"

scjones@sdrc.UUCP (Larry Jones) (09/09/89)

In article <471@sagpd1.UUCP>, jharkins@sagpd1.UUCP (Jim Harkins) writes:
> Due to some hardware considerations I have a special block of memory that I
> have to use for storage of some variables.  Lets say it starts at address FOO.
> In C, whats the best way to say "integer fred in normal mem, struct wilma
> somewhere after FOO, struct barney somewhere after FOO, struct bam_bam in
> normal mem", etc?  The best I can come up with is
> 
> pointer = FOO
> struct a *wilma = pointer
> pointer += sizeof(struct a)
> struct b *barney = pointer
> pointer += sizeof(struct b) * NUMBER_OF_BARNEYS     /* array of barneys */

I would suggest packaging all of the variables you want to be in
the special memory into a single struct and then declaring a
pointer to that struct that is initialized appropriately.

	struct special {
	   struct a wilma;
	   struct b barney;
	   } *p = (struct special *)FOO;

That solves the problem for static allocation, if you ever need
dynamic allocation then you still have to write a malloc.
----
Larry Jones                         UUCP: uunet!sdrc!scjones
SDRC                                      scjones@SDRC.UU.NET
2000 Eastman Dr.                    BIX:  ltl
Milford, OH  45150-2789             AT&T: (513) 576-2070
"I have plenty of good sense.  I just choose to ignore it."
-Calvin