I have this line of code here where I am trying to type cast two void arguments as strings and then use the strcmp function to compare the two:
int compareFirstName(const void * p1, const void * p2)
{
const char **str1, **str2;
str1 = (char **) &p1;
str2 = (char **) &p2;
return strcmp(*str1, *str2);
}
However, I keep getting the error,
assignment from incompatible pointer type [-Werror]
str1 = (char **) &p1;
^
I am pretty sure I am casting right, so I do not know what the problem seems to be. Before, I had a segmentation fault error but resolved it and am now stuck here.
EDIT: This is the struct I am using to compare the first names, IDS, and last names. Turns out I have to convert the void * into Student *, which I am a bit confused about
typedef struct
{
int ID;
char firstname[NAME_LENGTH] ;
char lastname[NAME_LENGTH] ;
} Student;
CodePudding user response:
You are not trying to cast as "strings" only to pointer to pointer to char which has nothing in common with the C strings.
You also do not want to get the reference to the local parameters p1
and p2
You want:
int compareFirstName(const void * p1, const void * p2)
{
const char *str1, *str2;
str1 = p1;
str2 = p2;
return strcmp(str1, str2);
}
or just enough
int compareFirstName(const void * p1, const void * p2)
{
return strcmp(p1, p2);
}
CodePudding user response:
Considering the question is slightly different than what it was before, I have decided to post a new answer:
int compareFirstName(const void * p1, const void * p2)
{
const Student *s1, *s2;
s1 = p1;
s1 = p2;
return strcmp(s1->firstname, s2->firstname);
}
This is the way to cast the void *
arguments to the structs that you typedef'ed as Student
. Then because p1 and p2 are pointers to structs, you need to use ->
to access the members.