-
Unexpected terimnation
why does this program terminate unexpedly when the control reaches line no.33
Code:
#include<stdio.h>
#include<string.h>
void swap(char *, char *);
void sort(int (*)(const char *, const char *), void(*)(char *,char *), char*[]);
int main()
{
char *names[] = {"rakesh", "rakshas" , "Kalantari" , "phisaddi"}; int i;
void swap(char *,char *);
sort(strcmp, swap, names);
for(i=0;i<4;i++)
printf("\n%s",names[i]);
}
void sort(int (*strcmp)(const char *, const char *), void (*swap)(char *,char *), char **name)
{
int i,j;
for(i=1;i<=3;i++)
for(j=1;j<=4-i;j++)
if(strcmp(name[j-1],name[j])>0)
swap(name[j-1],name[j]);
}
void swap(char *s, char *t)
{
char temp[10];
strcpy(temp,t);
strcpy(t,s);
strcpy(s,temp);
}
-
The problem is that the pointers point to the first character of string literals. As such, modifying what the pointers point to results in undefined behaviour.
If you want to swap the strings, you have to swap the pointers, not use strcpy to write to what the pointers point to.