To compare string using library function, i learnt to write a comparison function to compare two strings, but im not really clear about why are they doing this.
int StrCmp(const void *a, const void *b){
char *s1 = *(char**) a;
char *s2 = *(char**) b;
return strcmp(s1,s2);
}
Why do they have to cast it to char ** first?
why not just cast them to char * directly?
like
return strcmp((char*)a, (char*)b);
Whats the meaning of casting ( a pointer) to ( a pointer to pointer)
If i have
char *x = "string";
if i do casting for x
(char**)x; // what is this? Is this character 's'?
Im quite confuse with this, thanks for clarify
and one more question is about the const
if it is a const, can i still cast them?(altought i know i can)
“Why do they have to cast it to (char pointer pointer) first?
why not just cast them to (char pointer) directly?”
They have to cast it to what it is. Assuming the value
coming in points to memory location 10,000, you have
something like this:
If you cast it to a (char *) you are telling the compiler
that the address referred to by a (in this case 10,000) is a char.
Which is not correct.
“Whats the meaning of casting ( a pointer) to ( a pointer to pointer) If i have
char *x = “string”;
if i do casting for x
(char**)x; // what is this? Is this character ‘s’?”
What exists in this example is something like:
If you tell the compiler that x is a char** then it thinks this
is the pattern:
It incorrectly ends up going to whatever “address” the first 8 bytes starting at 30000 resolves to and getting a “character”. But since 30000 is the
start of a null-terminated character array, at best it goes to some part of memory and gets some random byte, thinking it is a valid char. At worst it will get an address that is invalid for this program, causing a fatal error when it tries to access it.
so can i just do
No, because a and b are not char pointers. To get char pointers you can’t avoid:
Using Linden’s example you would call like so: