Kai Kai - 1 year ago 141
C++ Question

Array of pointers to store addresses and print them later

I'm trying to use an array of pointers to store the addresses of some double values, which are also stored in an array.

My problem is, that I'm able to print the addresses but not the actual values, which they point to. I've come up with the following. When I try to add a star (cout << *ptrArr[i] << endl;), I get a error message that says, that it's not a pointer.

const int size = 3;
double var[size] = { 0.0, 0.1, 0.2};
int *ptrArr = new int[size];

for (int i = 0; i < size; i++) {
ptrArr[i] = (int)&var[i]; // assign the address of integer.
}

for (int i = 0; i < size; i++) {
cout << "Value of var[" << i << "] = ";
cout << ptrArr[i] << endl;
}

delete ptrArr;

Answer Source

Did you want to get this? Use a double* array, to store the addresses:

const int size = 3;
double var[size] = {0.0, 0.1, 0.2};
double **ptrArr = new double*[size];

for (int i = 0; i < size; i++) {
    ptrArr[i] = &var[i]; // assign the address of the double.
}

for (int i = 0; i < size; i++) {
    cout << "Value of var[" << i << "] = ";
    cout << *ptrArr[i] << endl;

    cout << "Address of var[" << i << "] = ";
    cout << ptrArr[i] << endl;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download