问题
Referring to the line with the comment:
- Why does adding parenthesis in the example work to print all the contents of the array?
The example prints "one", then prints garbage.
#include <iostream>
int main() {
const char* a[3] = { "one", "two", "three" };
const char*(*p)[3] = &a;
for(int i = 0; i < 3; i++) {
std::cout << *p[i] << std::endl; // this line
}
return 0;
}
It works after changing to this:
std::cout << (*p)[i] << std::endl;
回答1:
p is a pointer to an array of 3 elements like this:
┌─────┬─────┬─────┐
│ │ │ │
└─────┴─────┴─────┘
^
└─ p
Note that it points at the whole array, not a single element of it.
The expression *p[i] is treated as *(p[i]) due to operator precedence (which is equivalent to *(*(p + i))). This means that you are indexing the pointer to the array. If you do p[1], for example, you move the pointer along to the "next" array and attempt to dereference it:
┌─────┬─────┬─────┐
│ │ │ │
└─────┴─────┴─────┘
^
└─ p + 1
As we can see, there is nothing there, and you'll get undefined behaviour. However, when you do (*p)[i] (equivalent to *((*p) + i)), you are making sure the dereference happens first. The dereference gives us the array itself, which can then be implicitly converted by array-to-pointer conversion to a pointer to the arrays first element. So what you get is:
┌─────┬─────┬─────┐
│ │ │ │
└─────┴─────┴─────┘
^
└─ *p
In this case, the pointer is pointing at the array element and not the whole array. If you then index, for example, (*p)[1], you'll get:
┌─────┬─────┬─────┐
│ │ │ │
└─────┴─────┴─────┘
^
└─ (*p) + 1
This gives you a valid const char* which can then be outputted by cout.
回答2:
Operator precedence.Without () operator [] will be called first and result of it will be dereferenced. With () - firstly will be dereference and then call to operator [].
回答3:
Operator precedence.
The array selection have higher precedence than dereference, so from the compilers point of view it's really:
*(p[i])
回答4:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1,2,3,4,5};
int *p=arr;
int intgerSize=sizeof(int);
for(int k=0;k<5;k++)
{
cout<<"arr ["<<k<<"] "<<*(p+(k*sizeof(int)/intgerSize));
cout<<" "<<(p+(k*sizeof(int)/intgerSize));
cout<<" "<<p+k<<"\n";
}`enter code here`
return 0;
}
OUTPUT:-
arr [0] 1 0x7ffd180f5800 0x7ffd180f5800
arr [1] 2 0x7ffd180f5804 0x7ffd180f5804
arr [2] 3 0x7ffd180f5808 0x7ffd180f5808
arr [3] 4 0x7ffd180f580c 0x7ffd180f580c
arr [4] 5 0x7ffd180f5810 0x7ffd180f5810
来源:https://stackoverflow.com/questions/16013450/dereferencing-a-pointer-to-an-array