Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading