-5

The following code allocates a 10 element array of pointers to doubles.

int i=0;

double* dp[10];


for (int i = 0; i < 10; ++i)
{
    *(dp[i]) = 0.0;
}
for (int i = 0; i < 10; ++i)
{
    cout<< *dp[i]<< endl;
}

Now how do I initialize each of these doubles to 0.0.

Umar Gul
  • 7
  • 2
  • 5

2 Answers2

1

Write a loop that allocates space for each double and initializes it:

for (i = 0; i < 10; i++) {
    dp[i] = new double;
    *(dp[i]) = 0.0;
};

Are you sure you really need an array of pointers, not just an array of doubles? The latter would be simpler:

double dp[10] = {};

The empty initializer list defaults all the elements to 0.0.

Barmar
  • 669,327
  • 51
  • 454
  • 560
-1

Example with std::vector:

std::vector<double*> myArray(10);
std::fill(myArray.begin(), myArray.end(), new double(0.0));

(prefer classes from STL instead of C-style array in C++)

vincentp
  • 1,365
  • 8
  • 12