// increaser
#include <iostream>
usingnamespace std;
void increase (void* data, int psize)
{
if ( psize == sizeof(char) )
{ char* pchar; pchar=(char*)data; ++(*pchar); }
elseif (psize == sizeof(int) )
{ int* pint; pint=(int*)data; ++(*pint); }
}
int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;
}
I don't quite understand what line 8 is doing. I get that it creates a pointer but I don't understand the rest of the line. The code increments the next letter in the alphabet, it's in the tutorials and I've been reading it over and over trying to get it to make sense.
What do you mean by 'reinterpret the memory address', does this mean change it? It certainly looks like it, but the char* in brackets is confusing me. it looks like it's trying to typecast something but I'm sure that's not it.
>.> I dun think it's wise for me to get into a debate about whether it's a good technique or not!
void means unknown type. So there is an address pointed by a pointer to void. How to interpret this memory area? The code suggests to do the following: if the second parameter is equal to 1 that is to sizeof( char ) then to interpret the memory address as an object of type char and increase it.
No DTS, it looks like it's manipulating the bits... for instance when >> or << makes something go up a power, in this case it's simply incrementing the ...memory address?
(okay...might not actually have a clue what the hell...)
void pointers were used back in C when you didn't have polymorphism. They are not needed in C++ anymore, and they are bad in general.
The benefit: you indicate that it could be any type to readers of your code
The downside: you don't know what type it actually is and could interpret it as the wrong type
@Ravenshade: imagine you have a device but you don't know what it is used for. You can use it for smashing rocks or you could use it for opening doors, this is what "void *" allows for you. At the same time, using it for bashing rocks may or may not break it and kill you(r program).
Oh I get the advantages of the void type...I hardly ever use them except to reorganise code. In this context I understand why void has been used. It's because it can take multiple data types. (newb programmer alert!!!!)
Though it still doesn't explain the purpose of "pchar= (char*)data". Just what on earth are those brackets doing...surely it can't be an 'if' function?