Reputation: 103
The question is to alphabetically sort the given string inputs in ascending order. I wrote the following code for the same. But after printing the entered names the program instead of sorting the strings is giving segmentation fault. I have spent good time over the issue but couldn't figure out anything. Any help would be appreciated.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int x,i,j,length;
printf("Enter the number of names you want to sort.\n");
scanf("%d",&x);
char *names[x],*p,name[50],*t;
printf("Enter the names:\n");
for(i=0;i<x;i++)
{
scanf(" %[^\n]",name);
length = strlen(name);
p = (char *)malloc(length+1);
strcpy(p,name);
names[i] = p;
}
printf("Entered names are:\n\n");
for(i=0;i<x;i++)
{
printf("%s\n",names[i]);
}
printf("\n\nThe sorted names are:\n");
for(i=0;i<x-1;i++)
{
for(j=i+1;j<x;j++)
{
if(strcmp(names[i],names[j])>0)
{
strcpy(t,names[i]);
strcpy(names[i],names[j]);
strcpy(names[j],t);
}
}
}
for(i=0;i<x;i++)
{
printf("%s\n",names[i]);
}
return 0;
}
Upvotes: 2
Views: 94
Reputation: 3117
You didn't allocate t
so the strcpy(t,names[i])
will segfault.
You can also use strdup()
1 to duplicate your strings (instead of malloc()
and strcpy()
).
And, as your array is of char*
elements, you can just swap them directly:
t=names[i];
names[i]=names[j];
names[j]=t;
Regarding your question about pointers, you can consider pointers as uint32_t
: they are ”just" values you can assign, like regular integers. It's just their value that is interpreted as an address, rather than a random integer (i.e. its value has a special meaning for the computer, as it is strongly linked to memory).
1: As noted by @WhozCraig, strdup()
is not part of the standard library so you'll have to #include
the appropriate headers for your platform (it is really widely spread though and hardly a problem).
Upvotes: 6