GeekInterview.com
Series: Subject: Topic:
Question: 22 of 587

A program in C using Void Pointer

Code
  1. #include<stdio.h>
  2. #include<conio.h>
  3. int main()
  4. {
  5.  int a=10;
  6.  void *p;
  7.  p=&a;
  8.  clrscr();
  9.  printf("%u",*p);
  10.  getch();
  11.  return;
  12. }
Copyright GeekInterview.com

I know that this program is wrong as error is shown on compiling it. Anyone please provide a simple program using Void pointer in C. Thanks in advance :)
Asked by: KRIPA SHANKAR | Member Since Jul-2012 | Asked on: Jul 8th, 2012

View all questions by KRIPA SHANKAR

Showing Answers 1 - 2 of 2 Answers
Sereche

Answered On : Jul 8th, 2012

View all answers by Sereche

Your error is on line 9, where youve attempted to dereference a pointer to void (the expression *p). You can only dereference typed pointers. The solution you are probably looking for would be to replace line 9 with

printf("%u", *(int*)p);


A pointer stores a memory address (typically a 32-bit or 64-bit unsigned integer, depending on compiler options) that points to an object of the specified type. Dereferencing the pointer returns the object at this memory address, as that specified type. Declaring a void pointer declares a memory address, but without specifying the type of object contained at that memory location. As such, the compiler does not have enough information to know what data you are trying to access.

In most cases you should avoid using void pointers, since they remove any type safety. This can have negative consequences if you try to dereference a void pointer as the wrong type. Using a typed pointer prevents these mistakes, without adding any additional run-time costs.

Yes  2 Users have rated as useful.
  
Login to rate this answer.
Ashok Kumar Orupalli

Answered On : Sep 3rd, 2012

You have to typecast void pointer to int as *(int*)p;

Code
  1. #include<stdio.h>
  2. #include<conio.h>
  3. int main()
  4. {
  5.  int a=10;
  6.  void *p;
  7.  p=&a;
  8.  clrscr();
  9.  printf("%u",*(int*)p);
  10.  getch();
  11.  return 0;
  12. }

  
Login to rate this answer.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.