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)
Entry point main
should be defined as
int main()
or (with arguments)
int main(int argc, char* argv[])
but may or may not return some value.
In function swap
you are accessing uninitialized pointer which causes undefined behavior. There is no need to use pointer. Use plain char
.
void swap(char *a,char *b)
{
char t;
t=*a;
*a=*b;
*b=t;
}
Also to avoid buffer overflow, you should tell scanf()
how many characters to scan from input buffer
scanf("%19s",a[i]);
and check if scanning succeeded.
Now you should get correct results. Here is fixed code.