Q: List alphabetically a list in C? The program receives the following list:
Google
Apple
Microsoft
Samsung

And I want to sort this alphabetically.
I wrote the following program but I get segmentation fault while running it.
#include<stdio.h>
#include<string.h>
int main()
{
    char a[20][20],str[20];
    int i;
    FILE *file;
    file=fopen("./test.txt","r");
    if(file == NULL)
        printf("FILE NOT Opened...\n");
    for(i=0;i<5;i++)
    {
        if(fgets(str, 20, file) != NULL)
            {
              strcpy(a[i], str);
              printf("%s",a[i]);
            }
        }
    char *tmp;
    tmp = malloc(20); // still same error
    int j;
    for(i=0; a[i]; i++) {
        for(j = 0; a[j]; j++) {
            if(strcmp(a[i], a[j]) < 0) {
                strcpy(tmp,a[i]);
                strcpy(a[i],a[j]);
                strcpy(a[j],tmp);
            }
        }
    }
    for(i = 0; a[i]; i++) printf("%s\n", a[i]);
        return 0;
}


A: As bruceg suggested, your for loops need work. And, you may want to strip the newline.
Also, keep a count of the number of lines.
I've also done some further cleanup:
#include <stdio.h>
#include <string.h>

#define NLINES  20
#define LWID    20

int
main()
{
    char a[NLINES][LWID];
    char tmp[LWID];
    char *cp;
    int count;
    int i;
    int j;
    FILE *file;

    file = fopen("./test.txt", "r");
    if (file == NULL)
        printf("FILE NOT Opened...\n");

    for (count = 0; count < NLINES; count++) {
        if (fgets(tmp, LWID, file) == NULL)
            break;

        cp = strchr(tmp,'\n');
        if (cp != NULL)
            *cp = 0;

        strcpy(a[count], tmp);
        printf(" %s", a[count]);
    }
    printf("\n");

    fclose(file);

    for (i = 0; i < count; i++) {
        for (j = 0; j < count; j++) {
            if (strcmp(a[i], a[j]) < 0) {
                strcpy(tmp, a[i]);
                strcpy(a[i], a[j]);
                strcpy(a[j], tmp);
            }
        }
    }

    for (i = 0; i < count; i++)
        printf("%s\n", a[i]);

    return 0;
}


Here is the output:
 Google Apple Microsoft Samsung
Apple
Google
Microsoft
Samsung

