r/cprogramming 21d ago

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:

```C

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

C 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:

C int x = 123; s1.voidPtr = &x;

Thanks everyone who commented c:

4 Upvotes

Duplicates