C语言中为何使用*(&i)而非直接使用变量i?
*(&i) Instead of Just i? Great question! You’re totally right that in your simple C program:
int main() { int i = 5; printf("Simple value of i = %d", i); printf("\nPointer value of i = %d", *(&i)); return 0; }
both i and *(&i) output the same value (5). Let’s break down why this redundant-looking syntax exists and when it’s useful:
Teaching pointer fundamentals: This is the most common reason you’ll see
*(&i)in examples. It’s a tangible way to demonstrate how the address-of operator (&) and dereference operator (*) complement each other.&igrabs the memory address whereiis stored, and*on that address retrieves the value at that location. It’s a hands-on way to reinforce that variables are just names for memory locations, and pointers let you interact with those locations directly.Preparing for real-world pointer use: While
*(&i)is pointless in this trivial case, it mirrors patterns you’ll use constantly with dynamic memory or function calls. For example:- When you allocate memory with
malloc, you get a pointer back—you have to dereference it to access the stored value (*my_ptr). - When passing variables to functions by reference (to modify the original variable), you pass
&ito the function, which then uses*paramto read/write the original value. Your example is a simplified version of this flow.
- When you allocate memory with
Advanced low-level scenarios: Rarely, you might use
*(&i)to force the compiler to treat the variable as a dereferenced pointer, which can matter for type casting or memory manipulation. For example, if you needed to cast the address ofito a different pointer type (likechar*) and then dereference it to inspect individual bytes—though this is advanced and not common in basic code.
In day-to-day coding, you’d never write *(&i) instead of just i—it’s redundant and makes your code less readable. But it’s an excellent learning tool to wrap your head around how pointers and memory work in C.
内容的提问来源于stack exchange,提问作者gs650x

