简体   繁体   中英

type casting in c for constant pointer

I am trying to run this code, but the compiler returns the following warning:

int c=23;
int *const a=&c;
printf("%d",(int)a);

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

 printf("%d",(int)a);

You have declared a as a constant pointer, but you are trying to print it as an int . Use the %p specifier in order to print the address of your pointer and cast your pointer as void, like this:

printf ("%p", ( void * ) a);

You receive a warning because after type mismatch, the compiler must convert it to print it and information will be lost.

If you want to print the physical address of the pointer, use %p and cast the pointer to void * :

printf("%p", (void *) a);

If you want to print the contents of the pointer ( to which it's pointing to), you must dereference it:

printf("%d", *a);

Remember, to access the content, use * . Otherwise you work with the pointer, not its contents. To get the address of a non-pointer variable: & .

c represents an address in memory that is the first byte of an integer - in this case the number 23 a represents another address in memory that is the first byte of a pointer - in this case holding the address of c (not the value in c because you used &c which means its address)

To print out a in a meaningfull way printf must use the pointer format %p

If you use these four printf statements:

printf("%p\n", a);
printf("%p\n", &c);
printf("%d\n", *a);
printf("%d\n", c);

you will get something like this:

0x7ffc080a3f24   ('a' contains a pointer which is the address of 'c')  
0x7ffc080a3f24   (&c is the address of 'c')  
23               (*a, dereferencing the pointer contained in 'a' provides the value held by the address held by 'a')  
23               (and 'c' is the value held at the address &c)

Note that you will also get a warning if you do this:

printf("%p\n", (int) a);

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
because you are using the right format specifier for the pointer 'a', but you have cast it to the integer type. Whilst both int and a pointer are 'integers' they are different size integers.
If you ignore the warning and run the code, the value printed is not correct, but you can see that it has been truncated: 0x80a3f24

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM