How to use pointers in C language to sort strings

In C language, strings can be sorted using pointers. Here is an example code demonstrating how to sort strings using pointers.

#include <stdio.h>
#include <string.h>

void sortStrings(char* strings[], int n) {
    char* temp;

    for (int i = 0; i < n-1; i++) {
        for (int j = i+1; j < n; j++) {
            if (strcmp(strings[i], strings[j]) > 0) {
                temp = strings[i];
                strings[i] = strings[j];
                strings[j] = temp;
            }
        }
    }
}

int main() {
    char* strings[] = {"orange", "apple", "banana", "grape"};
    int n = sizeof(strings) / sizeof(strings[0]);

    printf("Before sorting:\n");
    for (int i = 0; i < n; i++) {
        printf("%s\n", strings[i]);
    }

    sortStrings(strings, n);

    printf("\nAfter sorting:\n");
    for (int i = 0; i < n; i++) {
        printf("%s\n", strings[i]);
    }

    return 0;
}

In the above example, we first define a function called sortStrings that takes a pointer to a string array and the size of the array as parameters. Within the function, we use nested loops to compare the strings and swap positions based on the comparison results to achieve sorting.

Then, in the main function, we define a string array named strings and obtain its size using the sizeof operator. Next, we call the sortStrings function to sort the strings. Finally, we output the results before and after sorting.

When you run the code above, it will output the following results:

Before sorting:
orange
apple
banana
grape

After sorting:
apple
banana
grape
orange

After sorting, the array of strings is arranged in alphabetical order.

bannerAds