fork download
  1. // C program to read Student records
  2. // like id, name and age,
  3. // and display them in sorted order by Name
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8.  
  9. // struct person with 3 fields
  10. struct Student {
  11. char* name;
  12. int id;
  13. char age;
  14. };
  15.  
  16. // setting up rules for comparison
  17. // to sort the students based on names
  18. int comparator(const void* p0, const void* p1)
  19. {
  20. struct Student* ps0 = *(struct Student**) p0;
  21. struct Student* ps1 = *(struct Student**) p1;
  22. return strcmp( ps0->name, ps1->name);
  23. }
  24.  
  25. // Driver program
  26. int main()
  27. {
  28. int i = 0, n = 5;
  29.  
  30. struct Student * arr = (struct Student *)malloc(n * sizeof(struct Student));
  31. // Get the students data
  32. arr[0].id = 1;
  33. arr[0].name = "bd";
  34. arr[0].age = 12;
  35.  
  36. arr[1].id = 2;
  37. arr[1].name = "ba";
  38. arr[1].age = 10;
  39.  
  40. arr[2].id = 3;
  41. arr[2].name = "bc";
  42. arr[2].age = 8;
  43.  
  44. arr[3].id = 4;
  45. arr[3].name = "aaz";
  46. arr[3].age = 9;
  47.  
  48. arr[4].id = 5;
  49. arr[4].name = "az";
  50. arr[4].age = 10;
  51.  
  52. // Print the Unsorted Structure
  53. printf("Unsorted Student Records:\n");
  54. for (i = 0; i < n; i++) {
  55. printf("Id = %d, Name = %s, Age = %d \n",
  56. arr[i].id, arr[i].name, arr[i].age);
  57. }
  58. // Sort the structure
  59. // based on the specified comparator
  60. qsort(arr, n, sizeof(struct Student *),comparator);
  61.  
  62. // Print the Sorted Structure
  63. printf("\n\nStudent Records sorted by Name:\n");
  64. for (i = 0; i < n; i++) {
  65. printf("Id = %d, Name = %s, Age = %d \n",
  66. arr[i].id, arr[i].name, arr[i].age);
  67. }
  68.  
  69. return 0;
  70. }
  71.  
Runtime error #stdin #stdout 0s 4296KB
stdin
Standard input is empty
stdout
Standard output is empty