void *ptr = malloc(9);
printf("%X", ptr); //this shows the value of memory pointed to by ptr
The previous line shoud have been:
printf("%p", ptr); //this shows the value of ptr
"%X"
is for int
, using it for pointers invokes UB, meaning anything can happen.
//I want to try to see what ever is at the memory location by dereferenced ptr
printf("%c", (*ptr)); // try to dereference the pointer
Because void
is an incomplete type, it cannot be dereferenced. Cast to a pointer of the desired type first, then we can talk. For char
that line would be:
printf("%c", *(char*)ptr); // try to dereference the pointer
But if you try to use a value before assigning it, beware of trap representations and other fun stuff.
Some more tips for you:
- Always compile with all warnings enabled. Add options
"-Wall -Wextra -pedantic"
- Decide on C or C++. This example works same for both though.
- Get the standard, or at least the last working draft. Wikipedia has pointers to them.
- If you post a question here, try to include a short, concise example, which can be compiled immediately. This time it was good anyway.