This blog is under construction

Wednesday 25 December 2013

Array of pointer to structure

Array of pointer to structure is nothing but an array whose elements are pointers to structure

How to declare array of pointer to structure?
Below is an example declaration for array of pointer to structure.
struct student *arr[10];
Here, arr is an array 10 of pointer to structure student.

Dynamic memory allocation:
Below is the procedure to perform dynamic memory allocation for the structure pointers in an array.
struct student {
int age;
char name[32];
};

fun() {
int i = 0;
struct student *arr[10];
for (i = 0; i < 10; i++) {
/* dynamic memory allocation for 5 structure objects */
arr[i] = (struct student *)malloc(sizeof(struct student) * 5);
}
}

Write a c program to pass an array of structure pointers to another function


  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  struct student {
        int age, rollno;
        char name[32];
  };

  /* printing details of students */
  void printData(struct student *arr[2]) {
        int i;
        for (i = 0; i < 2; i++) {
                printf("\nStudent %d:", i + 1);
                printf("Name: %s\n", arr[i]->name);
                printf("Roll: %d\n", arr[i]->rollno);
                printf("Age : %d\n\n", arr[i]->age);
        }
        return;
  }

  int main() {
        int i;
        struct student *arr[2];

        /* dynamic memory allocation for structure pointer in array arr */
        for (i = 0; i < 2; i++) {
                arr[i] = (struct student *)malloc(sizeof(struct student));
        }

        /* assigning values to structure elements */
        strcpy(arr[0]->name, "Ram");
        arr[0]->age  = 10;
        arr[0]->rollno = 1000;
        strcpy(arr[1]->name, "Raj");
        arr[1]->age  = 11;
        arr[1]->rollno = 1001;
        printData(arr);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Student 1:
  Name: Ram
  Roll: 1000
  Age : 10

  Student 2:
  Name: Raj
  Roll: 1001
  Age : 11


No comments:

Post a Comment