plz.. help me .. how to arrange the set words in aphabetical order in c.its confusing me

Dani AI

Generated

A concise, practical approach: as hinted, use a string comparator and a library sort. Keep words as an array of NUL-terminated C strings (an array of char *) and call qsort with a comparator that calls strcmp. That avoids comparing pointer addresses and works for both compile-time lists and runtime input (allocate each word with malloc/strdup and remember to free later). asked for code; a minimal, correct pattern is shown below.

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

int cmpstr(const void *a, const void *b) {
    const char *const *pa = (const char *const *)a;
    const char *const *pb = (const char *const *)b;
    return strcmp(*pa, *pb);
}

int main(void) {
    char *words[] = { "orange", "apple", "Banana", "grape" };
    size_t n = sizeof words / sizeof words[0];

    qsort(words, n, sizeof words[0], cmpstr);

    for (size_t i = 0; i < n; ++i)
        puts(words[i]);

    return 0;
}

Notes and cautions: strcmp is case-sensitive (uppercase letters sort before lowercase in ASCII); use strcasecmp on POSIX or convert strings to a common case for case-insensitive ordering. For locale-aware ordering, use strcoll. When reading input with fgets, strip the trailing newline before sorting. If the number of words is not known up front, store pointers in a dynamically grown array (realloc) and free each allocated string at the end. , this pattern should make the alphabetical ordering straightforward and robust.

Recommended Answers

All 3 Replies

Hii Kalpana,

plese post your program code(whatever effort you have done) here, we'll surely help you.:)

You haven't yet met Mr. strcmp() I presume? ;)

but i cant got any idea.how to use strcmp() in this.
:help me plz

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.