Reputation: 23
I am beginner in C language and was learning about function pointer in C language. There I encountered a problem?
Write a compare function to sort by first character of name?
*int (firstnamecharcompar)(const void * a, const void * b))
Here is my code solution for this.
#include<stdlib.h>
#include<stdio.h>
#include <stdbool.h>
int compare1(const void *a,const void *b)
{
char *c = *(char**)a;
char *d = *(char**)b;
return c[0] - d[0];
//return ( *(char*)a[0] == *(char*)b[0] );
}
int main()
{
char str[3][10];
int i;
for(i=0;i<3;i++)
{
printf("Enter %d string => " , i+1 );
scanf("%s", str[i]);
printf("\n");
}
for(i=0;i<3;i++)
{
printf("%s ",str[i]);
}
qsort(str,3,10,compare1);
for(i=0;i<3;i++)
{
printf("%s ",str[i]);
}
return 0;
}
But my code is getting terminated without giving any output? What is problem with my code?
Upvotes: 2
Views: 65
Reputation: 120021
char *c = *(char**)a;
char *d = *(char**)b;
These lines would be valid if you were sorting an array of pointers to char
. You are in fact sorting an array of 10-element char
arrays. Adjust the casts accordingly:
char *c = *(char(*)[10])a;
char *d = *(char(*)[10])b;
Upvotes: 5