Void Pointers

I got this from http://www.cplusplus.com/doc/tutorial/pointers/
and void pointers.
(Question at last line)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 // increaser
#include <iostream>
using namespace std;

void increase (void* data, int psize)
{
  if ( psize == sizeof(char) )
  { char* pchar; pchar=(char*)data; ++(*pchar); }
  else if (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 << '\n';
  return 0;
}


Output: y, 1603

I don't understand why it says "y" shouldn't it just say x??
Hey, Unfortunately Im not nearly experienced enough to answer your question, but Im just here to say that at night(European time), Im pretty much the only around and you're much better of posting during our day light, which is in about 12 hours. I hope someone passes around though, goodluck :)
I'm not an expert or anything, but this is how I read the code and think it makes sense.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
char a = 'x';                               //initialize char a equal to 'x'

increase( &a, sizeof(a));              //throw address of a and int size of char into increase function

...


void increase (void* data, int psize)     //this type-casts your char address to a void type pointer
{
     if ( psize == sizeof(char) )    //this if statement is relevant for above function call
          {
          char* pchar;                   //new pointer to char type
          pchar = (char*) data;     //set pchar equal to input pointer, type-cast to char*
          ++(*pchar);                  //dereference the char* pointer, add 1; this changes x to y
          }
}





I thought the same.
But why adding 1 to x will make it y...? It doesn't change any hex value. It changes the value of the pointer which is x and then it does ++x well here is the problem why ++x is y??
Cpper wrote:
I thought the same.
But why adding 1 to x will make it y...? It doesn't change any hex value. It changes the value of the pointer which is x and then it does ++x well here is the problem why ++x is y??


A character is actually a number. The character "x" is actually the number 120. So by increasing x, it changed the number to 121, which is the character "y."

For an example, you could display the character "x" through its number:

1
2
3
4
int main() {
	char c = 120;
	std::cout << c << std::endl;
}


The above code would print out "x" just the same as if you were to do:

char c = 'x';

You can look at an ASCII chart to see the values which is placed with each of the characters.
Last edited on
Topic archived. No new replies allowed.