Convert integer pointer to integer

I tried the following code to check what happens when we convert an integer pointer to an integer.

#include<stdio.h> #include<stdlib.h> int main() { int *p; int a; p = (int *)malloc(sizeof(int)); *p = 10; a = (int)p; printf("%d\n",*p); printf("%d \n",a); return 0; } The output is : 10 135680008 

Can someone explain the concept associated with this transformation? Any links related to this topic will also be helpful.

+7
source share
3 answers

Apparently you are confusing the pointer with the contents of the pointer.

As an analogue of the real world, you can say that by pointing to a bird you want to turn your index finger into a bird. But between the type of "bird" and "finger" there is no connection.

Passing this analogy into your program: you convert an object pointing to your int to int . Since the C pointer is implemented as a “memory cell number”, and since many memory cells are available, it is obvious that (int)p will result in a very large number.

Casting is an unpleasant thing. It is a coincidence that pointers are completely analogous to integers. If they were implemented as "n th the address of the memory bank m th ", you would not ask this question, because there would be no obvious relationship, and you would not be able to do this.

+11
source

135680008 is the address in decimal format (it will be 0x8165008 in hexadecimal format) pointed to by p : the address of the memory area allocated with malloc .

+4
source

Here you print the memory address a , but you print it as a signed decimal integer. It doesn’t make much sense as a format, because some high memory addresses, an exact border depending on your word size and compiler will be printed as negative.

The standard should print it as an unsigned hexadecimal number with zeros up to 8 or 16 characters (indeed, it depends on the exact size of the word again). In printf this will be %#08X , so memory address 0x243 will be printed as 0x00000243.

+1
source

All Articles