c++ - Casting/dereferencing char pointers to a double array -
is there wrong casting double pointer char pointer? goal in following code change 1 element in 3 different ways.
double vec1[100]; double *vp = vec1; char *yp = (char*) vp; vp++; vec1[1] = 19.0; *vp = 12.0; *((double*) (yp + (1*sizeof (vec1[0])))) = 34.0;
casts of type fall category of "ok if know you're doing dangerous if don't".
for example, in case know pointer value of "yp" (it pointing double
) technically safe increase value size of double
, re-cast double*
.
a counter-example: suppose didn't know char*
came from...say, given function parameter. now, cast big problem: since char*
technically 1-byte-aligned , double
8-byte-aligned, can't sure if given 8-byte-aligned address. if it's aligned, arithmetic produce valid double*
; if not, crash when dereferenced.
this 1 example of how casts can go wrong. you're doing (at first glance) looks work in general have pay attention when cast things.
Comments
Post a Comment