C++指针与引用使用困惑求助:*与&的用法及报错问题
Hey there! I totally get how confusing pointers and references can be when you're just starting out with C++. Let's walk through each of your questions one by one to clear things up.
1. Why does int x = 10; int *pt; *pt = x; throw an error, and why do we need pt = &x;?
Let's break this down step by step:
- When you declare
int *pt;, you're creating a pointer variable calledptthat's designed to store the memory address of an integer. But right now,ptis a wild pointer—it hasn't been assigned to any valid memory address, so it's pointing to some random, unallocated spot in memory. - When you write
*pt = x;, you're trying to take that random memory location and assign the value ofx(10) to it. This is undefined behavior—your program might crash, throw an error, or do something totally unexpected because you're modifying memory that doesn't belong to your program.
The fix pt = &x; makes sense because:
&xgives you the actual memory address ofx. Assigning this address topttells the pointer, "Hey, point to the memory wherexis stored." Nowptis pointing to a valid location, and later you can use*ptto safely read or modify the value ofx.
2. Why is int x = 10; int *pt = &x; valid when *pt should represent the value, not the address?
This is a super common confusion because the * symbol does two very different things depending on context:
- In a variable declaration:
int *ptis telling the compiler, "ptis a pointer to an integer." Here, the*is part of the variable's type, not an operation to access a value. It's just C++'s way of declaring pointer variables. - When using the variable later:
*ptis the dereference operator, which lets you access the value stored at the addressptis pointing to.
So in int *pt = &x;, we're not assigning &x to *pt—we're assigning it to pt itself. It's exactly equivalent to writing:
int x = 10; int *pt; // Declare pt as a pointer to int pt = &x; // Assign x's address to pt
The combined line just does both steps in one, which is totally valid syntax.
3. Why is int &temp = &n1; wrong, but int &temp = n1; correct for sharing an address?
First, let's clarify: references are not pointers—they're aliases for existing variables. The & here has a different meaning than the "address-of" operator:
- When you write
int &temp, you're declaringtempas a reference to an integer. This meanstempwill be another name for the same variable you bind it to. &n1is the address-of operator, which gives you the memory address ofn1(a pointer value). But a reference can't be bound to an address—it has to be bound directly to an existing variable.
When you write int &temp = n1;, you're saying, "temp is just another name for n1." Now, any change to temp will affect n1 and vice versa, because they're the exact same piece of memory—no pointers involved here, just two names for the same variable.
内容的提问来源于stack exchange,提问作者3XBULL

