delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/01/27/03:37:46

From: G DOT DegliEsposti AT ads DOT it
To: djgpp AT delorie DOT com
Message-ID: <C1256599.002EA5EC.00@vega.ads.it>
Date: Tue, 27 Jan 1998 09:36:42 +0100
Subject: Re: HELP: accessing astructure members via VOID pointer??
Mime-Version: 1.0




>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?

Well, you can! You have to tweak it a little:

*((int *)bar) = 55

It is necessary to cast to an int *, otherwise the compiler doesn't know
how many bytes are affected by the assignment.

>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!!

I think this should work (actually it looks a bit too complicated, maybe
some of the brackets are not necessary :-)

*((int *)(((char *)bar) + 4)) = 55

BTW, why are you trying to do something so strange? :-)
Isn't the usual way enough  (I mean ((struct foo *)bar)->x = 55) ? :-)

ciao
  Giacomo



- Raw text -


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