Thursday, December 2, 2010

Use of Pointer in Structure in C programming


C program to illustrates the use of pointers in structure

# include< string.h>
# include< stdio.h>
# include< stdlib.h>
struct Record
{
            char *name;
            char *address;
            long pin;
};
/* This function will be used to sort the list according to name. structure type array variable will be created and address of the  first location and the number of locations, means records will  be passed as argument.*/
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();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner