I have written the following code to get sorted strings in a 2-D character array
#include <stdio.h>
#include <string.h>
void swap(char *,char *);
void main() {
char a[20][20];
int Pass = 0, i = 0, j = 0, n;
printf("\nHow many elements you want to sort ? >> ");
scanf("%d", &n);
printf("\n\nEnter the elements to be sorted :\n");
for (i = 0; i < n; i++)
scanf("%s", a[i]);
for (Pass = 1; Pass < n; Pass++) {
for (j = 0; j < n - Pass; j++)
if (strcmp(a[j], a[j + 1]) < 0)
swap(a[j], a[j + 1]);
printf("\n\nPass = %d\n", Pass);
for (i = 0; i < n; i++)
printf(" %s ", a[i]);
}
}
void swap(char *a, char *b) {
char *t;
*t = *a;
*a = *b;
*b = *t;
}
But, I get output as
How many elements you want to sort ? >> 5
Enter the elements to be sorted :
1 2 3 4 5
Pass = 1
2 3 4 5 1
Pass = 2
3 4 5 2 1
Pass = 3
4 5 3 2 1
Pass = 4
Segmentation fault (core dumped)
Why do I encounter segmentation fault? (the same code works properly if I use an integer array instead of a character array)