Tuesday, February 15, 2011

Use of pointer variables as structure member in C programming


So far we have used normal variables and arrays as structure item or variable. Now we will see how to use pointer variables as structure member.

The following program illustrates the use of pointers in structure.

# include< string.h>
# include< stdio.h>
# include< stdlib.h>
struct Record
{
            char *name;
            char *address;
            long pin;
};

void sort(struct Record *str, int n)
{
            int i,j;
            struct Record temp;
            for(i =0; i <n; i++)
            {
              for (j=i+1; j <n; j++)
              {
               if (strcmp (str[i].name, str[j].name)>0)
               {
                        temp = str[i];
                        str[i] = str[j];
                        str[j] = temp;
               }
              }
             }
}

void main()
{
            char choice;
            int i, n = 0;
            struct Record string[10];
            clrscr();
            printf("Input The List\n ");
            printf("\n**************\n");

do
{
 string[n].name = (char *) malloc(50*sizeof(char));
 string[n].address= (char *) malloc(100*sizeof(char));
printf("Name: ");
gets(string[n].name);
printf("\n Address: ");
gets(string[n].address);
printf("Pin Code: ");
scanf("%ld", &string[n].pin);
n++;
fflush(stdin);
printf("\n Input another y/n? ");
choice = getchar();
fflush(stdin);
}while(choice == 'y');
  printf("Unsorted list \n");
printf("\n********************\n");
for (i =0; i < n ; i++)
{
printf("\n %s", string[i].name);
printf("\n %s", string[i].address);
printf("\n %ld", string[i].pin);
printf("\n********************\n");
}
getch();
sort(string, n);
printf("\n Sorted list");
printf("\n********************\n");
for (i =0; i < n ; i++)
{
printf("\n %s", string[i].name);
printf("\n %s", string[i].address);
printf("\n %ld", string[i].pin);
printf("\n********************\n");
}
getch();
}

About the program

Name, address and pin number of several persons are stored in the structure type array.  In structure definition two char type pointers are used to store name and address. Locations to store name and address will be created dynamically.
The structure type array is ultimately sored according to names in ascending order and records are displayed.



No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner