May 132017
 
 C Tags:  Add comments

Generic programming, loosely means that the code we have written is type-independent. It is a larger topic, macros in C language also comes under generic programming. In this post we are only discussing generic pointers.

We know that pointers are strictly typed. i.e we cannot assign an integer memory address to float *.

int x = 5;
float* fp = &x; // ERROR
int *ip = &x; // OK

We know that all the pointers, irrespective of whether it is char*, int*, float* or any other data pointer, require same amount of memory (because they all store address). We have different data types because while dereferencing the pointer (finding the value at the address stored in the pointer) we need to know the total size of memory being pointed to, and that size come from the data types.

It make sense to have a pointer type that can hold the address of any data type. When a variable is declared as being a pointer to type void it is known as a generic pointer.

int x = 5;
float y = 3.5;
void* vp;   // GENERIC POINTER

vp = &x;  // OK
vp = &y;  // OK

The only problem is that a generic pointer cannot be directly dereferenced. We need to typecast it to relevant data type before dereferencing.

This is very useful when you want a pointer to point to data of different types at different times.

Below is the code from: http://www.nongnu.org/c-prog-book/online/x658.html

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;
}
pinkdiamonds.nl

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)