© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

15. What is a void pointer?

Ans:
A void pointer is a C convention for a raw address. The compiler has no idea what type of object a void Pointer really points to. If you write
int *ip;
ip points to an int. If you write
void *p;
p doesn’t point to a void!

In C and C++, any time you need a void pointer, you can use another pointer type. For example, if you have a char*, you can pass it to a function that expects a void*. You don’t even need to cast it. In C (but not in C++), you can use a void* any time you need any kind of pointer, without casting. (In C++, you need to cast it).

A void pointer is used for working with raw memory or for passing a pointer to an unspecified type.

Some C code operates on raw memory. When C was first invented, character pointers (char *) were used for that. Then people started getting confused about when a character pointer was a string, when it was a character array, and when it was raw memory.

Ex - 1:  Is this code legal?
int *ptr;
ptr = (int *) 0x400;

Ans::
                        Yes

Explanation:
The pointer ptr will point at the integer in the memory location 0x400.

Ex - 2 what is the output?:

main()
{
                        int a=10,*j;
            void *k;
                        j=k=&a;
            j++; 
                        k++;
            printf("\n %u %u ",j,k);
}

  
Ans:
Compiler error: Cannot increment a void pointer

Explanation:
Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type. No pointer arithmetic can be done on it and you cannot apply indirection operator (*) on void pointers.


SLogix Student Projects
bottom