Do something to improve things. Anything. Start small or go big. Just do something. Today. Now. The world will be better for it. ----Just because no one else believes in your dreams doesn't mean you shouldn't believe in your dreams. ----The world is the great gymnasium where we come to make ourselves strong. "Swami Vivekananda"

Government Jobs In India Headline Animator

21 July 2011

5. Generic pointer:


void pointer in c is known as generic pointer. Literal meaning of generic pointer is a pointer which can point type of data.

Example:


void *ptr;
Here ptr is generic pointer.


Important points about generic pointer in c?


1. We cannot dereference generic pointer.


#include "malloc.h"
void main(){
void *ptr;
printf("%d",*ptr);
}


Output: Compiler error


2. We can find the size of generic pointer using sizeof operator.


#include "string.h"
void main(){
void *ptr;
printf("%d",sizeof(ptr));
}


Output: 2


Explanation: Size of any type of near pointer in c is two byte.

3. Generic pointer can hold any type of pointers like char pointer, struct pointer, array of pointer etc without any typecasting.

Example:

void main(){
char c='A';
int i=4;
void *p;
char *q=&c;
int *r=&i;
p=q;
printf("%c",*(char *)p);
p=r;
printf("%d",*(int *)p);
}


Output: A4

4. Any type of pointer can hold generic pointer without any typecasting.

5. Generic pointers are used when we want to return such pointer which is applicable to all types of pointers. For example return type of malloc function is generic pointer because it can dynamically allocate the memory space to stores integer, float, structure etc. hence we type cast its return type to appropriate pointer type.



Examples:
1.
char *c;
c=(char *)malloc(sizeof(char));
2.
double *d;
d=(double *)malloc(sizeof(double));
3.
Struct student{
char *name;
int roll;
};
Struct student *stu;
Stu=(struct student *)malloc(sizeof(struct student));

No comments:

Subscribe via email

Enter your email address:

Delivered by FeedBurner

website-hit-counters.com
Provided by website-hit-counters.com site.