数组与指针的关系:为何C程序未打印a[i]却输出地址?
Hey there! Let's walk through this—this is one of the most common "wait, why is this happening?" moments when learning C arrays and pointers, so you're definitely not alone here.
First, let's nail down the key relationship between arrays and pointers in C:
- An array name (like
ain your code) acts as a constant pointer to the first element of the array. So if you haveint a[5];,ais equivalent to&a[0]—but you can't modify it (you can't doa++like you would with a regular pointer, since it's fixed to the start of the array). - The array subscript syntax
a[i]is actually just sugar for*(a + i)under the hood. C takes the pointer to the first element, addsitimes the size of the array's data type, then dereferences that address to get the value stored there. - Fun fact: You can even use subscript syntax with regular pointers! If you have
int *ptr = a;,ptr[i]works exactly likea[i]—the two are interchangeable here (the only difference is thatptris a modifiable pointer, whileais constant).
Now, why is your program printing addresses instead of the a[i] values? The most common culprits are:
Wrong
printfformat specifier
If you used%p(the specifier for printing memory addresses) instead of the specifier matching your array's type, C will treat the value ofa[i]as an address and print it. For example:int a[] = {10, 20, 30}; printf("%p", a[1]); // Oops! This prints the "address" represented by the value 20, not 20 itselfFix this by using the correct specifier:
%dfor integers,%ffor floats, etc. So the correct line would beprintf("%d", a[1]);.Printing the pointer itself instead of dereferencing it
If you accidentally wrotea + iinstead ofa[i](or*(a + i)), you're printing the memory address of the i-th element, not the value stored there. For example:int a[] = {10, 20, 30}; printf("%d", a + 1); // Prints the address of a[1], not 20To fix this, either use the subscript syntax
a[i]or explicitly dereference the pointer with*(a + i).
One quick extra note: When you pass an array to a function, the array name "decays" into a regular modifiable pointer. That means inside the function, you can do things like ptr++ to move through the array, even though you can't do that with the original array name in its defining scope.
Hope that clears up the confusion! If you share your actual code snippet, we can zero in on the exact line causing the issue—but these are the two most common reasons for this behavior.
内容的提问来源于stack exchange,提问作者Sriram Govardhanam

