Home > Enterprise >  What is the purpose of dereferencing a pointer, then getting its address and dereferencing that, in
What is the purpose of dereferencing a pointer, then getting its address and dereferencing that, in

Time:01-16

I ran into a weird code snippet while following an image processing guide. The language is C. What is the purpose of dereferencing a pointer, then dereferencing its address? 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.

  • Related