How to use a pointer to structure in C Programming?


When pointer to structure is incremented then the pointer points to the next block of
memory. As for example

struct rec
{
int a;
char b[10], *c;
};

main()
{
struct rec *obj;
obj=(struct rec *)malloc(sizeof(struct rec));
obj->a=10;
strcpy(obj->b, “XYZ”);
strcpy(obj->c, “ABC”);
printf (“\n%d\t%s\t%s”,obj->a, obj->b, obj->c);
//Incrementing pointer to structure
obj++;
obj->a=15;
strcpy(obj->b, “PQR”);
strcpy(obj->c, “MNO”);
printf (“\n%d\t%s\t%s”,obj->a, obj->b, obj->c);
}


pointer to structure in c


In the above program, dynamic memory allocation is used for assigning one block of structure
in obj. Later the pointer to structure (obj) is incremented, so that pointer points to the next
block of memory. 

Danger associated with increment of pointer to structure:

As in the above program structure member is a char pointer. When pointer to structure is incremented then it may results in memory overwrite, because the size for the pointer member is not defined.

Keywords: pointer to structure in c,how to use pointer for structure, use of pointer for structure,program to increment pointer