Hi,
I want to know about generic pointer.
Can someone please let me know about the term Generic Pointer with a simple example.
Hi,
I want to know about generic pointer.
Can someone please let me know about the term Generic Pointer with a simple example.
When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first. Hence the term Generic pointer.
This is very useful when you want a pointer to point to data of different types at different times.
Code:int main() { int i; char c; void *the_data; i = 6; c = 'a'; the_data = &i; printf("the_data points to the integer value %d\n", *(int*) the_data); the_data = &c; printf("the_data now points to the character %c\n", *(char*) the_data); return 0; }
Functions using generic pointers implement common utility for almost all objects of various types. One such function is the standard memcmp() function which compares the objects pointed by s1 and s2, in the below declaration, for equality. Its prototype is:
Internally, it casts s1 and s2 to pointers to character (signed or unsigned), and compares character-by-character till either of the following conditions occurs:Code:#include <string.h> int memcmp(const void *s1, const void *s2, size_t n);
a. characters pointed by character pointers are not equal; returns with a nonzero value
b. all n character pointed by internal character pointers have been compared to be equal; returns with 0
A "generic pointer" is not a specific term in programming C/C++ although it may, perhaps, be represented by a void *.
A void * is a pointer to a memory location without actually specifying what data that location stores.
Bookmarks