Reputation: 703
Because I followed a discussion where was told "Aliasing through incompatible pointer types is undefined behavior" (e.g. double d; int *p = (int *)&d;
following question:
Is it allowed to cast an (double *)
to (double **)
, e.g. double *d1; double **d2 = &d2
and using syntax like d2[0][y]
expecting to be the same as d1[y]
?
I know that it is not exactly aliasing through incompatible pointer types, but however I am not sure. Background is that I want to have a function which operates on 2-dimensional arrays (= images) but I want to be able to pass only a row or column of an image.
Upvotes: 1
Views: 130
Reputation: 153909
double**
is incompatible with double*
. The conversion is legal, but the only thing you can do with the results is cast it back. This seems more or less obvious: on a 32 bit machine, a double*
won't even have the same size as a double
.
But your example doesn't convert a double*
to double**
. It creates a new double**
, which points to the double*
. This is fine.
Upvotes: 5
Reputation: 76240
Is it allowed to cast an (double ) to (double *), e.g. double *d1; double **d2 = &d2 and using syntax like d2[0][y] expecting to be the same as d1[y]?
Of course not, and it won't even compile.
But if you meant:
double *d1;
double **d2 = &d2;
then yes, the above is perfectly valid and since d2[0][y]
can be seen as (*d2)[y]
, there's really no problem at all.
Finally, remember that in the above code, you are not casting anything: &d2
is already of type double**
. If you have to cast something, please use C++ style casts (static_cast
, dynamic_cast
, reinterpret_cast
, etc..) and not C style casts.
Upvotes: 1