//increase is a function that takes in data, a pointer to something, as well as the size of the
//data type pointed to by data (psize
#include <iostream>
usingnamespace std;
//increase is a function that takes in data, a pointer to something, as well as the size of the
//data type pointed to by data (psize). Based on psize, this function converts
//data to the appropriate pointer type and increments the value pointed to by one.
//Currently this function assumes that data points either to a char or an int
void increase (void*0 data, int psize)
{
if ( psize == sizeof(char) )
{
//here we know that data points to a char, because the size of
//the datatype matches that of char
char* pchar; //instantiate a pointer to a char
//convert data to be a pointer to a char, store the pointer in pchar
++(*pchar); //increment what pchar points to by one
}
elseif (psize == sizeof(int) )
{
//here we know that data points to an int, because the size of
//the datatype matches that of int
int* pint; //instantiate a pointer to an int
//convert data to be a pointer to an int, store the pointer in pint
++(*pint); //increment what pint points to by one
}
}
int main ()
{
char a = 'a';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
system ("Pause");
return 0;
}
/* How to invision the values
|Name | Value | Memory Address
|char | 0002 | 0001 char* pchar. so char's value becomes 0002
|pchar | 0001 | 0002
|data | 0002 | 0003 pchar = (char*) data. data points to char and becomes 0001
pchar ++ increases pchar to 0002.
//When Applied
| A | 0002 |0001
|B | 0001 |0002 A* B. So A's value becomes 0002
|C | 0002 |0003 b = (A*) C. C points to A and becomes 0001
|data | 0002 | 0003 B(0001) ++ = (0002)(&B) So it becomes B?
So is this right or is it just luck that this is how i got this? Ive been writing the cells on paper
like this to help me figure this problem out. According to the way i did this
you dont need pchar = (char*) data. I took it out of both voids and got the same answer....i think this is confusing me more
but i just cant seem to figure out pointers. Thank you. */
I don't understand why you're using void when templates is the more effective solution. You're using C code in a C++ program. While that's all gravy, it makes sense to use templates:
The really important thing in C++ is type. It is the basis of support for the programmer. However, C++ allows you to override the type system, but then you have to take full responsibility for the correct use of type.
By defining your function as:
void increase (void* data, int psize)
you are bypassing the type system. So inside the function, you have no idea what kind of pointer you've been passed. You then go on to guess what you have when you could know aprori by passing in the right type to begin with.
On you thing of size 1, did you know that a class cannot have a zero size? Guess what size you're likely to get if you define a class that has no members?