Dec 31, 2015

C Programming #54: Structure pointer

As you know structure variables are stored in memory and have address associated with it.  Just like any variable and its associated pointer; structure too can have pointers. This article will explore on structure pointers. At this point it is good if you could re-visit below article

  1. C Programming #41: Pointer - introduction 
  2. C Programming #53: Structure - introduction

Syntax


struct stype *ps;

ps is pointer to structure variable of type stype. Like any other pointer, sizeof of ps is 8 bytes in 64 bit computer and 4 byte in 32 bit computer.

Lets take a example to demonstrate how a structure pointer is used. (github source code link)

#include <stdio.h>

struct student {
   char name[20];
   int age;
   int class;
};

int main()
{
   struct student a = {"Ram", 7, 2};
   struct student b = {"Mason", 9, 4};
   struct student *pa = &a, *pb;

   pb = &b;

   printf("Student %s age is %d and studies in %d\n",
          pa->name, pa->age, pa->class);
   printf("Student %s age is %d and studies in %d\n",
          pb->name, pb->age, pb->class);

   if(pa->age > pb->age) {
      printf("%s is older\n", a.name);
   }else if(a.age < b.age) {
      printf("%s is older\n", b.name);
   }else {
      printf("%s and %s are both of same age\n",
             a.name, b.name);
   }
   return 0;
}

Output of the above program is

Student Ram age is 7 and studies in 2
Student Mason age is 9 and studies in 4
Mason is older

Structure pointer needs to point to structure of same type. Initialization can be done during declaration (shown in program with pa) or later (show in program with pb).While the structure member variable were accessed as a.name, using pointer special operator is used to do the same pa->name.  Note that it is same as (*pa).name. Since using * with pointer variable would always involve using braces (to bump up priority of the dereference operator - more details can be found in this article C Programming #16: Operator precedence, associativity and order of evalation) structure operator dereference operator is preferred.

Structure pointer is esp useful in passing pointer to function. Following function demonstrates it. (github source code link)


#include <stdio.h>

struct student {
   char name[20];
   int age;
   int class;
};

void print_student(struct student* ps);

int main()
{
   struct student a = {"Ram", 7, 2};
   struct student b = {"Mason", 9, 4};

   print_student(&a);
   print_student(&b);

   return 0;
}

void print_student(struct student* ps)
{
  printf("Student %s age is %d and studies in %d\n",
  ps->name, ps->age, ps->class);
}

Output of the above program is

Student Ram age is 7 and studies in 2
Student Mason age is 9 and studies in 4


Links

Next Article - C Programming #55: Structure declaration and definition
Previous Article - C Programming #53: Structure - introduction
All Article - C Programming

No comments :

Post a Comment