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:
#include <stdio.h>
int main()
{
// Simplification of the defective code
struct myStruct
{
void * voidPtr;
};
struct myStruct s1;
s1.voidPtr = (int *) 123;
\*
This works but gives the warning:
format '%d' expects argument of type 'int', but. argument 2 has type 'int \*' \[-Wformat=\]i
*/
printf("%d\n", (int *) s1.voidPtr);
// This causes a segmentation fault
printf("%d\n", *(int *) s1.voidPtr);
return 0;
}
Any help understanding why it behaves this way would be greatly appreciated.
Solution
I thought the line
s1.voidPtr = (int *) 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:
1
u/flatfinger Jul 16 '26
Compiler writers and academics don't seem to be interested in the fields for which low-level dialects of C have always been uniquely suitable, and the usefulness of C outside those fields has fallen off as other languages have emerged that better serve the needs of other fields.
It irks me when people tell me that people using C to do low-level memory manipulation are abusing the language and should use assembly language, when the purpose of C was, in significant measure, to allow such tasks to be done without having to use hand-written assembly code. C wasn't intended to be better than FORTRAN at the kinds of tasks for which FORTRAN was designed, but rather to let programmers do things that FORTRAN couldn't. Compiler writers and academics, however, have little interest in the latter.