I'm trying to initialize every element of an array of pointers to doubles with the associated value 0.0
.
I have the following code:
double* dp[10];
for (int i = 0; i < 10; i++) dp[i] = 0.0;
But this gives me Segmentation fault
and I'm not sure how to fix this.
I tried:
for (int i = 0; i < 10; i++) {
dp[i] = new double; // this seems to fix the segmentation problem.
*(dp[i]) = 0.0; // accessing the associated value in order to asign a new value
}
But I'm not sure if this is the correct way to do it. Could someone explain me the dynamic memory allocation in detail?
When double* dp[10]
is executed and an array of pointers is created. Those pointers: where do they point to in the memory? If anywhere, why can't I just use that place in the memory to store every double? Why do I have to specify new double
, isn't it obvious by the type of the pointers?
Sorry if I'm asking stupid questions, but I haven't fully understood (actually at all) how this works.
Thanks in advance!