Having an issue with printing a pointer out. Every time I try and compile the program below i get the following error:
pointers.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘int *’
I'm obviously missing something simple here, but from other examles of similar code that I have seen, this should be working.
Here's the code, any help would be great!
#include <stdio.h> int main(void) { int x = 99; int *pt1; pt1 = &x; printf("Value at p1: %d\n", *pt1); printf("Address of p1: %p\n", pt1); return 0; }
You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.
The format specifiers are used in C for input and output purposes. Using this concept the compiler can understand that what type of data is in a variable during taking input using the scanf() function and printing using printf() function. Here is a list of format specifiers. Format Specifier.
In C we have seen different format specifiers. Here we will see another format specifier called %p. This is used to print the pointer type data.
Simply cast your int pointer to a void one:
printf( "Address of p1: %p\n", ( void * )pt1 );
Your code is safe, but you are compiling with the -Wformat
warning flag, that will type check the calls to printf()
and scanf()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With