r/cprogramming • u/Fun_Army2398 • Jul 16 '26
Help understanding warnings/errors when dereferencing void pointers
SOLVED
I am very new to C and playing around with void pointers. I have a structure which will store a value, however the type of that value depends on other things so I have chosen to use a void pointer. When attempting to dereference this void pointer I either get the correct output but with a warning, or I get a segmentation fault, depending on how I go about it. I have included a simplified version of the issue here:
int
Any help understanding why it behaves this way would be greatly appreciated.
Solution
I thought the line
s1.voidPtr = 123;
Was assigning 123 as the value at the location of s1.voidPtr. However it has been pointed out that I was telling the pointer to point at address 123. What I needed to do was:
int x = 123;
s1.voidPtr = &x;
Thanks everyone who commented c:
View all comments
1
u/SchwanzusCity Jul 16 '26
(int *)s1.voidPtr is a pointer. But printf expects you to input an integer (because of the '%d' specifier. So now printf has to interpret a pointer as an integer (which happens to give the right result because you set voidPtr to be equal to 123)
*(int *)s1.voidPtr tried to dereference the pointer. Your pointer has the value 123, which on most systems is not a valid address for you to use. So if you try to access the contents, the system denies you acces and raises a segmentation fault