I am a beginner at C++ programming and I am working my way through the c++ Language tutorial from this site but I am having a little difficulty with the little example program increaser on page 72 which deals with void pointers
I have entered this code ,compiled and run it and it works as it should but I am not sure exactly how in particular the following lines
This is how I think it works,well part of it
line1 declares a prototype void function called increase which accepts 2 parameters a void pointer called data and an int variable called psize
In the body of the function the first if compares psize to sizeof(char)
and if they are equal runs the next line of the code. psize is the second parameter passed to the function later on in the program which is sizeof(a)
so what we are doing is comparing sizeof(a)with sizeof(char) for a char variable
they should both equal 1 so the next line will execute.
The next if else does the same for int variables but comparing psize with sizeof(int) and so detecting Int variables.
It is lines 2 & 4 where I become confused and some help to explain these would
be much appreciated (assuming that I have got it correct so far which I might not have)
First, that isn't a prototype. It is a function definition. A prototype for that function would look like
void increase (void*, int)
and is used to tell the compiler that that function exists and allows a function to call it before it is defined as the code you provided does.
What this code is doing is determing if the variable data is of type char or type int and then applying it to the appropriate type pointer. So, if it is the size of a char variable the first if statement is executed. First, it is declaring a pointer to type char called pchar, then it is initializing the pointer to point to data, but since data is of type void pointer it must be cast to a char pointer. Then it is incrementing the value of I believe the pointer. It could also be incrementing the value stored in the location pointed at by the pointer, but like I said, I'm not for sure.
The next if block does the same thing, except it is setting it to a pointer of type int called pint.
Much clearer now. I thought I was somewhere on the on the right track and now you have explained about casting the void* pointer to a char* pointer it makes much more sense.