954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

problem in void pointer

I am facing a problem in void pointers in c++. Have a look at the following code:

#include<iostream.h>
int main()
{
	void *ptr;
	int x=3;
	float y=2.35f;
	char c='A';
	ptr=&x;
	cout<<endl<<*ptr; //line 1
	ptr=&y;
	cout<<endl<<*ptr;// line 2
	ptr=&c;
	cout<<endl<<*ptr;//line 3

	cout<<endl;
	return 0;
}

I am getting the errors of illegal indirection at line 1,2,3.Please help!!!

amitahlawat20
Light Poster
30 posts since Mar 2008
Reputation Points: 10
Solved Threads: 2
 

you cannot dereference a void pointer (what would you get? a void?) what are you trying to accomplish anyway?

bugmenot
Posting Whiz in Training
225 posts since Nov 2006
Reputation Points: 53
Solved Threads: 34
 

A short tutorial on pointers
http://www.cplusplus.com/doc/tutorial/pointers.html
Also pointers to void (i.e. void *) are discussed there ...

mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395
 

If you want to get to the data that a pointer to void points to, you need to cast it into the correct type first:

#include <iostream>

int main()
{
  using namespace std;

  int x = 3;
  float y = 2.35f;
  char c = 'A';
  void *ptr;

  ptr = &x;
  cout<< *static_cast<int*>(ptr) <<'\n';

  ptr = &y;
  cout<< *static_cast<float*>(ptr) <<'\n';

  ptr = &c;
  cout<< *static_cast<char*>(ptr) <<'\n';
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

I'm confused as to why you are using a void pointer. I don't think that that would ever be useful. Although I'm probably wrong...

skatamatic
Posting Shark
959 posts since Nov 2007
Reputation Points: 403
Solved Threads: 129
 

Hello...

As such all are saying that your assignment is of no use, they are correct.....

But still if you want to clear the compiler hurdles, you can do one thing... Explicit type case all the things in your code...

Means write like this :
ptr=&x;
cout<

sahil_itprof
Newbie Poster
10 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You