This blog is under construction

Monday, 14 May 2012

Pointer to structure in C

Pointer holds the address of another variable.  The variable may be of any data type int, float, char etc.  We can define pointer to a structure in the same way.  And the data members of a structure can be accessed using pointers.  We can call pointer to structure as structure pointer(s).

Consider the following example,
struct student {
     char name[100];
     int rank, rollno;
};

struct student *obj1;
obj1 = (struct student *)malloc(sizeof(struct student));

To access data members of structure using structure pointer, arrow operator(->) is used as shown below.  Please note that the structure pointer won't point to any valid memory location initially.  We need to either allocate memory dynamically or assign some valid memory to structure pointer before accessing data members in a structure using structure pointer.

Example:
obj1->name, obj1->rank, obj1->rollno;


Example C program using structure pointer:

  #include <stdio.h>
  #include <string.h>

  struct student {
        char name[100];
        int rank;
  };

  int main() {
        struct student *s1;
        s1 = (struct student *)malloc(sizeof (struct student));
        strcpy(s1->name, "Tom Hanks");
        s1->rank = 1;
        printf("Name:%s\nRank:%d\n", s1->name, s1->rank);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Name:Tom Hanks
  Rank:1



No comments:

Post a Comment