Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

C Pointer address of difference

int main() {
    
    int *x;
    int *y;

    y = x;

    printf("%p %p", &x,&y); // prints 0061FF1C 0061FF18
    printf("%p %p", x, y); // prints 00400080 00400080

    return 0;
}

Why don't these print the same thing? I thought using just the x and the &x would get to the same value. Also, why are the bottom ones matching if the top one's arent?

question from:https://stackoverflow.com/questions/66055564/c-pointer-address-of-difference

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

1 Reply

0 votes
by (71.8m points)

When you say y = x in this case it just means that y assumes whatever pointer value x happened to have. You never initialized x with a value, so it's just some random junk.

The address of x and y themselves is going to be different. These are two separate variables representing two separate pointers. You can assign their value to be the same, but their address remains distinct.

You're probably confusing this behaviour with:

int x = 5;
int* y = &x;

Where now y == &x but &x and &y continue to remain distinct.

As C does not have references, you really don't have situations where two independent variables are ever the same address.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...