Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer will not work in printf()

Tags:

c

pointers

printf

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;     } 
like image 608
Chris Avatar asked Mar 24 '11 10:03

Chris


People also ask

Can you printf a pointer?

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.

What is format specifier for pointer in C?

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.

What is %P in C printf?

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.


1 Answers

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().

like image 86
Macmade Avatar answered Nov 04 '22 11:11

Macmade