Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

c - Conversion of integer pointer to integer

Tried following code to check what happens when we convert integer pointer to a 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
",*p);
         printf("%d 
",a);
         return 0;
 }

 The output is : 10
                 135680008

Can anyone explain, the concept related to this conversion? Any links provided related to this topic would also be helpful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Apparently you confuse the pointer with the content of the pointer.

As an analogy to the real world, you could say that, with me pointing at a bird, you want to convert my index finger to a bird. But there is no relation between the type 'bird' and 'finger'.

Transferring that analogy to your program: you are converting the object pointing to your int to an int itself. Since a C pointer is implemented as 'the number of a memory cell', and since there are lots of memory cells available, it's obvious that (int)p will result in a very big number.

Casting is a nasty thing. It's a coincidence that pointers are quite analogous to integers. If they were implemented as "the nth address of the mth memory bank", you wouldn't be asking this question because there wouldn't have been an obvious relation, and you wouldn't have been able to do this cast.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...