Skip to Content, PHP, MySQL, Javascript, Ajax, Htacces

C Language Pointer Interview Questions and Answers For Freshers Part-3

Be First!

c-program-pointers5. What is a void pointer?

A void pointer is a C convention for “a raw address.” The compiler has no idea what type of object a voidpointer “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 achar*, 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.)

6. When is a void pointer used?

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.

For example, strcpy() is used to copy data from one string to another, and strncpy() is used to copy at most a certain length string to another:

char *strcpy( char *str1, const char *str2 );

char *strncpy( char *str1, const char *str2, size_t n );

memcpy() is used to move data from one location to another:

void *memcpy( void *addr1, void *addr2, size_t n );

void pointers are used to mean that this is raw memory being copied. NUL characters (zero bytes) aren’t significant, and just about anything can be copied. Consider the following code:

#include “thingie.h”    /* defines struct thingie */

struct thingie  *p_src, *p_dest;

/* … */

memcpy( p_dest, p_src, sizeof( struct thingie) * numThingies );

This program is manipulating some sort of object stored in a struct thingie. p1 and p2 point to arrays, or parts of arrays, of struct thingies. The program wants to copy numThingies of these, starting at the one pointed to by p_src, to the part of the array beginning at the element pointed to by p_dest. memcpy() treats p_src andp_dest as pointers to raw memory; sizeof( struct thingie) * numThingies is the number of bytes to be copied.



Leave a Reply