0

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!!

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Sunil
  • 11
  • 2
  • If you are a beginner, why don't you be patient until you reach the level that teaches you that? – machine_1 Sep 23 '17 at 05:51
  • 1
    do you know something about pointers, for starters ? – Pac0 Sep 23 '17 at 08:52
  • Possible duplicate of [What is the difference between const int\*, const int \* const, and int const \*?](https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const) – Alessandro Da Rugna Sep 23 '17 at 10:33
  • @machine_1 ., I have worked some stuff in C, bt i still believe myself as beginner.. And discouraging someone is not appriciatable... – Sunil Sep 23 '17 at 16:21
  • @AlessandroDaRugna No it isn't, in your mentioned question, they have asked just the intoduction but i know all that stuff and diff. B/w const int*, int* const and so on, but i was cared about its application in my specified statement! – Sunil Sep 25 '17 at 02:42

1 Answers1

1

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, structs 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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
leyanpan
  • 433
  • 2
  • 9
  • Is that void * works like a python variable,I mean we can use it for any data type and "any no. of times" .Is that each time,we can declare it in different type ? @leyanpan – Sunil Sep 23 '17 at 07:15
  • No. void * is a pointer (which does not exist in python, I think) and only stores an address (you can consider it as an integer i that means some data is stored starting from the i'th byte of the memory, although this is not actually the case). You can only cast it into other types of pointers (struct str_name* etc) because all of them stores an address in memory and they are actually the same thing but treated differently when compiling. Your cast only makes sense if there is already an object stored at p of type (struct str_name). The type of variable cannot change in C. – leyanpan Sep 23 '17 at 07:27
  • can i do the cast more than once(each time with different type) – Sunil Sep 23 '17 at 09:52