I am a beginner in C/C++, I was unable to understand, what exactly is done in this code:
const void *p; //declaration of p used above
Thanks in advance!!
I am a beginner in C/C++, I was unable to understand, what exactly is done in this code:
const void *p; //declaration of p used above
Thanks in advance!!
Pointers store addresses (locations) in memory, so the data (location) stored in the pointer itself does not depend on the actual type that was stored in that location of the memory.
When you declare a pointer of type void *
, it basically means that the pointer stores the address of an variable/object that can be any type (int
, float
, struct
s etc). It does not make sense to directly access the data stored in a void pointer without knowing what type of data is stored there.
When you use
((struct str_name*)p)->str_dataitem;
you explicitly tell the compiler that it should treat the memory at (and following) p
as if it stores an object of type struct str_name
and access the str_dataitem
member within that structure stored at p
.