What is the purpose of dereferencing a pointer, then getting its address and dereferencing that, in C?

Advertisements

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];

>Solution :

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.

Leave a Reply Cancel reply