Write a C program to illustrate structure pointers.
#include <stdlib.h>
struct voterID {
char name[100], dob[100], addr[100];
int age, id;
};
int main() {
int n, i;
struct voterID *ptr;
/* get the no of entries from user */
printf("Enter the number of inputs:");
scanf("%d", &n);
/* dynamically allocate memory store the input entries */
ptr = (struct voterID *)malloc(sizeof (struct voterID) * n);
/* get the input entries from user using pointers */
printf("Enter your inputs:\n");
for (i = 0; i < n; i++) {
getchar();
printf("Name:");
/* get the input using pointer - ptr[i].name*/
fgets((ptr + i)->name, 100, stdin);
printf("Data of Birth:");
fgets((ptr + i)->dob, 100, stdin);
printf("Address:");
fgets((ptr + i)->addr, 100, stdin);
printf("Age and ID:");
scanf("%d%d", &(ptr + i)->age, &(ptr + i)->id);
}
/* print the outputs */
printf("\nOutput:");
for (i = 0; i < n; i++) {
printf("\nCitizen %d:\n", i + 1);
printf("Name : %s", (ptr + i)->name);
printf("Date of Birth : %s", (ptr + i)->dob);
printf("Address : %s", (ptr + i)->addr);
printf("Age : %d\n", (ptr + i)->age);
printf("Voter ID : %d\n", (ptr + i)->id);
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of inputs:2
Enter your inputs:
Name:Adam
Data of Birth:23/04/1989
Address:Chennai
Age and ID:24 1234
Name: Sandler
Data of Birth:23/04/1988
Address:Mumbai
Age and ID:25 2345
Output:
Citizen 1:
Name : Adam
Date of Birth : 23/04/1989
Address : Chennai
Age : 24
Voter ID : 1234
Citizen 2:
Name : Sandler
Date of Birth : 23/04/1988
Address : Mumbai
Age : 25
Voter ID : 2345
Enter the number of inputs:2
Enter your inputs:
Name:Adam
Data of Birth:23/04/1989
Address:Chennai
Age and ID:24 1234
Name: Sandler
Data of Birth:23/04/1988
Address:Mumbai
Age and ID:25 2345
Output:
Citizen 1:
Name : Adam
Date of Birth : 23/04/1989
Address : Chennai
Age : 24
Voter ID : 1234
Citizen 2:
Name : Sandler
Date of Birth : 23/04/1988
Address : Mumbai
Age : 25
Voter ID : 2345
No comments:
Post a Comment