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 :)

Questions by KRIPA SHANKAR

Showing Answers 1 - 6 of 6 Answers

Sereche

  • Jul 8th, 2012
 

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.

Ashok Kumar Orupalli

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

  Was this answer useful?  Yes

Give your answer:

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

 

Related Answered Questions

 

Related Open Questions