Home »
C/C++ Data Structure Programs
C program to sort structure items using qsort() with a function pointer
In this tutorial, we will learn about the qsort() function and how to sort structure items using qsort() with a function pointer using C program?
By Nidhi Last updated : August 06, 2023
Problem statement
Here, we will create a structure for 5 students. Then we will arrange student information in ascending order using the qsort() function based on student names and then print sorted student detail on the console screen.
qsort() function
The qsort() is a standard library function in C programming language that is used to sort an array. As the name suggests, the qsort() function uses the quick sort algorithm to sort a given array. The syntax is,
void qsort (void* base, size_t num, size_t size,
int (*comparator)(const void*,const void*));
C program to sort structure items using qsort() with a function pointer
The source code to sort structure items using qsort() with function pointer is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to sort structure items
// using qsort() with function pointer
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
char name[16];
int id;
} Student;
int strCmp(const void* strA, const void* strB)
{
const char* str1 = (const char*)strA;
const char* str2 = (const char*)strB;
return (strcmp(str1, str2));
}
int main()
{
Student rec[5];
int i, j;
strcpy(rec[0].name, "ABC");
rec[0].id = 500;
strcpy(rec[1].name, "PQR");
rec[1].id = 400;
strcpy(rec[2].name, "XYZ");
rec[2].id = 100;
strcpy(rec[3].name, "LMN");
rec[3].id = 200;
strcpy(rec[4].name, "TUV");
rec[4].id = 300;
qsort(rec, 5, sizeof(Student), strCmp);
printf("Sorted Structure elements: ");
for (i = 0; i < 5; i++)
printf("\n%s\t%d", rec[i].name, rec[i].id);
printf("\n");
return 0;
}
Output
Sorted Structure elements:
ABC 500
LMN 200
PQR 400
TUV 300
XYZ 100
Explanation
In the above program, we created two functions strCmp() and main(). The strCmp() is used to compare two string items.
In the main() function, we created an array of integers arr with 5 elements. Then we sorted the elements of structure using the qsort() function and printed the sorted student detail on the console screen.