View Single Post
Old Jan 2nd, 2007, 4:17 AM   #1
Soulstorm
Hobbyist Programmer
 
Soulstorm's Avatar
 
Join Date: Jan 2006
Location: Menidi, Athens, Greece
Posts: 243
Rep Power: 3 Soulstorm is on a distinguished road
Void Pointers Question about dereferencing

I have been experimenting with void pointers. I have encountered many problems, since I want to implement them into a very big project, but I made some examples that I believe that if I understand them, I will be able to use them efficiently.

Here is my first example:
cpp Syntax (Toggle Plain Text)
  1. int main (int argc, char * const argv[]) {
  2. int *p;
  3. int a = 100;
  4. void *v;
  5. p = &a;
  6. v = p;
  7. std::cout << v;
  8. return 0;
  9. }

The result I am getting is '0xbffff9c0' from the cout function. Actually, I had predicted it, but I don't know how can I access the contents of the void pointer. Can you help?

Another example:

cpp Syntax (Toggle Plain Text)
  1. void f(void *p){
  2. printf("%s",p);
  3. }
  4.  
  5. int main (int argc, char * const argv[]) {
  6. char p[] = "hello!";
  7. f(p);
  8. return 0;
  9. }
The above code works as expected. It shows 'hello'. But if I replace the printf fuunction with the cout:
cpp Syntax (Toggle Plain Text)
  1. void f(void *p){
  2. cout << p;
  3. }
  4.  
  5. int main (int argc, char * const argv[]) {
  6. char p[] = "hello!";
  7. f(p);
  8. return 0;
  9. }
I get an address! (0xbffff9b8).

Can you please explain to me why this is happenning (in both examples) and what can I do to dereference a void pointer so that I can access the elements it points to?
__________________
Project::Soulstorm (personal homepage)
Soulstorm is offline   Reply With Quote