0

I know that a void pointer is useful for setting up generic functions etc. In any case, I also understand that a void pointer can be used to directly point to things like integers etc. I suspect that a void pointer can also be used to point to structure items as well; however, I can't seem to get the semantics related to a passing a void pointer into a structure. Specifically, i'm trying to change fcat.test from 200 to 300 by using the void pointer. No-matter, which permutation of casting i use, I get the following error "main.c:12:15: error: request for member ‘test’ in something not a structure or union." How do I go about accessing a structure via a void pointer and changing the values within it? My code is below.

#include <stdio.h>
typedef struct _cat{
    int test;
}cat;

int main()
{
cat fcat;
fcat.test=200;
void * pointer=NULL;
pointer=&fcat;  //This works
*((cat)pointer.test)=300; //I can't seem to figure out how to get 300 into the function via the void pointer.  I've tried (cat *) as the typecast along with the -> operator after pointer.  Nothing works.
}
3
  • 1
    ((cat *)pointer)->test = 300 -- just need to remember that prefix ops (like cast) are lower precedence than postfix (like ->) Commented Aug 5, 2024 at 1:13
  • That works, thank you! How do I know when to use the instance of the struct vs the struct type? Both ((cat *)pointer)->test = 300 and ((struct _cat *)pointer)->test=300 work. Regardless, you're response works. Commented Aug 5, 2024 at 1:21
  • 1
    Because of the typedef struct _cat and cat are the same thing and interchangeable in all cases. Commented Aug 5, 2024 at 1:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.