For a 4-D array, I’m trying to average the values using compact pointer notation. Using examples from my text, it says I can use something like this:
void DisplayAverage(double (*set)[DIM1][DIM2][DIM3])
double *ptr;
double subTotal2 = 0;
for (ptr = (double *)set; ptr < (double *)set + DIM0 * DIM1 * DIM2 * DIM3; ptr++) {
subTotal2 += *ptr;
subTotal2 /= (DIM0 * DIM1 * DIM2 * DIM3);
cout << "Using compact pointer operations, total: " << subTotal2 << "\n";
}
}
That code works. However, if I try to use another notation from the text:
for (ptr = (double *)set; ptr < (double *)(&set + 1); ptr++) {
to access the array, I get no output. Any thoughts? Thanks.
You have one address-of too much:
You were adding one to the address of your parameter (and thus were pointing to nowhereland), instead of
DIM0to the value of your parameter (which will bring you to after the array data, which is your goal).Notice that the parameter is a pointer to an array of dimensions
[DIM1][DIM2][DIM3]. In other words, the argument you pass to the function can be an array of typedouble[DIM0][DIM1][DIM2][DIM3], which will decay to the pointer type of that parameter. You haveDIM0rows, so you addDIM0to that pointer to reach the position after the last cell.What you were probably having in mind was adding one to the pointer to the whole array. This will work if you have the following declaration, instead.
You now need to pass the argument using
&arginstead of justarg, to actually pass the address of the array, instead of letting it decay to its inner dimension type. The loop can then be written as