delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/01/27/13:31:47

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: HELP: accessing astructure members via VOID pointer??
Date: Tue, 27 Jan 1998 13:24:07 -0500
Organization: Two pounds of chaos and a pinch of salt.
Lines: 68
Message-ID: <34CE2647.1333@cs.com>
References: <34CD4681 DOT 3747 AT cam DOT org>
NNTP-Posting-Host: ppp229.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Vic wrote:
> 
> Hello. I'd like to be able to do something like this:
> I have a struct foo (int x,y,z) and a void* bar=&foo;
> So bar holds the adress of foo. I know that at the beginning of the
> struct lies the first member. so why can't I just say *bar=55 or
> something?
> I'd like to be able to access any member of a struct using a pointer.
> Like, if I want to access the second member, I add 4(or whatever) to the
> pointer and write the value to that adress. How could I do that? HELP!!
> TIA,

There are two main ways to do this.  The first is to perform the proper
pointer arithmetic and then cast the result to 'int *', as was mentioned
in another post.  The other way is to cast the pointer itself to type
'struct foo *' and then dereference it like any other structure pointer:

  ((struct foo *) bar )->x;

However, that obviously defeats the purpose of your code, and is
therefore not very useful.

What you are doing is extremely awkward.  It can be made to work, but
it's a non-trivial task and is very difficult for anybody else to
understand.  For what you're doing, it would probably be more effective
to use an array of integers and then index the array to get the value
you want:

  struct foo { int vals[3] );

or more simply:

  int vals[3];

A really classy alternative, if you don't mind the extra work, is to
combine both approaches by using a union instead of a struct.  The
following (tested) should allow you to access the struct values as both
discrete variables and as an array of integers:

  union foo
  {
      struct
      {
          int x, y, z;
      } i;
      int a[3];
  };

  union foo bar;
  union foo *baz;

  bar.i.x = 20;
  bar.i.y = 30;
  bar.i.z = 40;
  printf( "%d %d %d\n", bar.a[0], bar.a[1], bar.a[2] );

  baz = &bar;
  printf( "%d %d %d\n", baz->i.x, baz->a[1], *(baz->a + 2) );

Hope this helps!

-- 
---------------------------------------------------------------------
|      John M. Aldrich       | "If 'everybody knows' such-and-such, |
|       aka Fighteer I       | then it ain't so, by at least ten    |
|   mailto:fighteer AT cs DOT com   | thousand to one."                    |
| http://www.cs.com/fighteer |                 - Lazarus Long       |
---------------------------------------------------------------------

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019