I ran into a weird code snippet while following an image processing guide. The language is C. What is the purpose of taking an address, casting the pointer, then dereferencing it? I am new to C, so I am unsure if this is a common practice and its purpose.
unsigned char header[];
// not sure why we are dereferencing the array then getting its address and casting it into an int pointer then dereferencing that.
int width = *(int *)&header[18];
int height = *(int *)&header[22];
int bitDepth = *(int *)&header[28];
// why not this?
int width = (int) header[18];
int height = (int) header[22];
int bitDepth = (int) header[28];
CodePudding user response:
It seems the type of the pointer header
is not int *
. Maybe it has the type void *
or char *
or unsigned char *
.
So to get an integer you need to cast the pointer to the type int *
and then to dereference it to get the value pointed to by the pointer.
CodePudding user response:
The type that &
returns is a pointer type. In this case, it is a pointer to the 18th element of the array (17th if you start from the zeroth element).
(int *) &header[18];
(int *)
is then casting the pointer type returned by &
to an int
pointer, or int *
.
*(int *) &header[18];
The *
then dereferences that int
pointer, or int *
, to initialize width
.
Now, to answer your question: Why the cast?
Because the type of the pointer header
might not be an int *
, hence the cast.
CodePudding user response:
I am unsure if this is a common practice and its purpose.
Code like this is a problem.
Aliasing
The behavior of this code is not defined by the C standard because it violates the aliasing rules in C 2018 6.5 7. (Other) answers tell you what the author of the code may have intended to do, but code like this should not be used without a guarantee from the compiler that it supports this aliasing. You should avoid writing code like this.
@Eric Postpischil
Alignment
(int *)&header[18]
and others risks alignment failure and undefined behavior (UB). Don't do it.
Endian
Result is endian dependent. Proceed with caution.