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

int main()
	void *ptr;
	int x=3;
	float y=2.35f;
	char c='A';
	cout<<endl<<*ptr; //line 1
	cout<<endl<<*ptr;// line 2
	cout<<endl<<*ptr;//line 3

	return 0;

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

Re: problem in void pointer 80 80

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

Re: problem in void pointer 80 80

A short tutorial on pointers
Also pointers to void (i.e. void *) are discussed there ...

Re: problem in void pointer 80 80

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';
Re: problem in void pointer 80 80

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...

Re: problem in void pointer 80 80


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 :
cout<<endl<<(int *)ptr;

But my frnd, lemme clear thet the output will be undesirable as you are confused with void*...

I think you havnt used the void * in correct manner....

You can use void * when you don't know the exact datatype....
They provide such a flexibilty to be converted in any pointer type... But explicit typecasting is required......
This was not happening in C but in CPP it will generate error...

void *p;
int *q;
int j;
q = &j;
p = q; //Works
q = p;//Compiler will flag an error

So go in this manner, you will get cleared....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.