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

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

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';
}

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

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<<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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.