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
1.2k views
in Technique[技术] by (71.8m points)

c - Assigning/Casting integers to pointers

#include<stdio.h>

#define int int*

main(){
    int *p,q;
    p=(int *)5;
    q=10;
    printf("%d",q+p);
}

my question is that in line p=(int *)5, and q=10 how it's working internally exactly because p and q are both pointer types, how is it possible that we can assign an integer value to pointer variable q?. One more thing how this type casting p=(int*)5 working here ?

By using this formula we can answer

new address = old address+number * sizeof data type to which pointer is pointing

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

#define int int* will replace int *p, q as int* *p, q. So Here p is double pointer to int and q is of type int.

For example consider the below program of your same logic in char

#include<stdio.h>  
#define char char*  
main()
{     
    char *p,q;     
    printf("%d, %d
", sizeof(p), sizeof(q));
} 

Output is

4, 1

p=(int *)5; - This statement also will be replaced like p=(int* *)5; by preporcessor. So its not throwing any warning.

so now printf("%d",q+p); will gives you 45 in case of 32 bit machine or 85 incase of 64 bit machine.


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

...