简体   繁体   中英

Dereferencing an element of an array of pointers

So recently in class, we were introduced to pointers and heaps and how they work. A question I have is why cant we cout a dereferenced pointer in that array? For example, in the code below:

#include <iostream>
using namespace std;

int main() {

    double* p = new double[2];
    *(p + 0) = 37.5;
    *(p + 1) = 101.4;

    for (int i = 0; i < 2; i++)
        cout << *p[i] << endl;

    return 0;

}

Why doesn't cout << *p[i] work but cout << *(p + i) does?

In C, the name of an array is a pointer to the first element. C++ inherited that from C. In your program, p is the pointer to the first element of the array. So you either do pointer arithmetics as you did when setting the elements (eg *(p + 1) = 101.4;) or you use the subscript operator ([]) to do the arithmetics: *(p + i) is the same as p[i]. The compiler translates p[i] to 1) adding i to p and then 2) access the address that resulted from the sum. That is exactly what you have written: *(p + 1). The statement in the parentheses is calculated first and the reference operator is applied to this result. That is exactly what happens if you use the index operator instead. So your loop has to look like this:

for (int i = 0; i < 2; i++)
{
 std::cout << p[i] << std::endl;
}

Because of the precedence of operators your statement *p[i] translates to *(p[i]). So this statement tries to use the double read from the array as an address that shall be accessed. That this is not possible, is obvious (hopefully).

Got it?

PS: And please, do yourself a favor and ALWAYS surround the body of for/while/if statements with curly brackets. That saves you a LOT of time (especially debugging your own nonsense). Trust me, it is true.

cout << p[i]; 

should work as you expect because *p[i] basically is *(*(p + i))

read here for me https://www.tutorialspoint.com/cplusplus/cpp_pointer_arithmatic.htm http://www.learncpp.com/cpp-tutorial/6-8a-pointer-arithmetic-and-array-indexing/

p[1] = *(p + 1) it is what you want to do. The [] operator already dereferences. *p[1] = *(*(p + 1)) it tries to dereference a double Wich cannot happen

Note that p[i] is same as *(p+i). Now *p[i] is meaningless, unless p[i] itself points to a different location, for eg

int t=0;

for(int i = 0; i < 2 ;i++)
   p[i] = &t;

cout << *p[i] << "is nothing but value of t" << endl;

I hope it is clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM