C Online Compiler
Example: qsort Strings Alphabetical in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// qsort Strings Alphabetical #include <stdio.h> #include <stdlib.h> // For qsort #include <string.h> // For strcmp // Comparison function for strings (alphabetical order) int compareStrings(const void *a, const void *b) { // The elements of the array are char*, so a and b are pointers to char* const char *str_a = *(const char **)a; // Cast void* to char** and then dereference to get char* const char *str_b = *(const char **)b; // Cast void* to char** and then dereference to get char* return strcmp(str_a, str_b); // Use strcmp for string comparison } int main() { // Step 1: Initialize an array of strings (array of char pointers) char *fruits[] = {"banana", "apple", "grape", "orange", "kiwi", "pineapple"}; int n = sizeof(fruits) / sizeof(fruits[0]); printf("Original strings:\n"); for (int i = 0; i < n; i++) { printf("- %s\n", fruits[i]); } printf("\n"); // Step 2: Sort the array of strings qsort(fruits, n, sizeof(char *), compareStrings); printf("Sorted strings (alphabetical):\n"); for (int i = 0; i < n; i++) { printf("- %s\n", fruits[i]); } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS