From: horst DOT kraemer AT snafu DOT de (Horst Kraemer) Newsgroups: comp.os.msdos.djgpp Subject: Re: help: void pointers Date: Sat, 07 Aug 1999 10:44:15 GMT Organization: [Posted via] Interactive Networx Message-ID: <37abee37.246073100@news.snafu.de> References: <8UQq3.6777$K%6 DOT 145927 AT news1 DOT rdc2 DOT on DOT home DOT com> NNTP-Posting-Host: n241-171.berlin.snafu.de X-Newsreader: Forte Free Agent 1.11/32.235 Lines: 77 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com On Sat, 07 Aug 1999 07:04:36 GMT, "YUBS" wrote: > Hi, I'm having some trouble using void pointers. I'm writing a function that > will allocate enough memory for any of my types by using a void pointer as a > parameter in the function. I.e. > void pcx_init (void *image, char type) > So say I have the following type: > typdef struct pcx_image_typ > { > char *buffer; > int width, height; > } pcx_image, *pcx_image_ptr > I want to be able to pass a pointer to a variable of type pcx_image to > pcx_init and have it allocate width*height memory for buffer. The problem > I'm getting is that DJGPP keeps complaining that I'm "dereferencing "void *" > pointer" and that "request for memeber "buffer" in something not a structure > or a union". > > here's my exact code: > > void pcx_init(void *image, char type) > { > switch (type) > { > case 's': { > if (!(((pcx_image_ptr)(image->buffer)) = (char > * )malloc (image->width* image->height))) > } > } > } Of course. image is a pointer to _void_ and therefore image->buffer etc. is meaningless. If I understand you correctly pcx_init has a void* parameter because it shall be used for different structure types. In this case you'd have to cast 'index' to the appropriate type every time _before_ you applying the -> operator to it. It's not (pcx_image_ptr)(image->buffer) which is casting the illegal expression (image->buffer) but ((pcx_image_ptr)image)->buffer which is casting 'image' and then dereferences it. Better readable would be a simple case 's': { pcx_image_ptr p = image; if ( (p->buffer=malloc(p->width * p->height))==NULL ) {/**/} ... break; } using a local helper variable instead of the verbose and terrible ((pcx_image_ptr)index)->buffer = malloc( ((pcx_image_ptr)index)->width * ((pcx_image_ptr)index)->height ); Regards Horst