Reputation: 13
I am trying to take in two strings via command line arguments in C and then compare them. I know that malloc
returns a void
pointer although I do not understand how to pass this to my compare function because it is looking for a const void
pointer. I assume I will have to cast the pointers that point to the memory on the heap where the strings will be allocated (?) although I'm not sure how to go about this, any help is appreciated.
int cmpstringp(const void *arg1, const void *arg2);
int main(int argc, char **argv) {
char *strOne;
char *strTwo;
int n = 10;
strOne = (char *)malloc((n + 1) * sizeof(char));
strTwo = (char *)malloc((n + 1) * sizeof(char));
strOne = argv[1];
strTwo - argv[2];
cmpstringp(strOne, strTwo);
}
int cmpstringp(const void *arg1, const void *arg2) {
const char * const * ptr1 = (const char **)arg1;
const char * const * ptr2 = (const char **)arg2;
const char *str1 = *ptr1;
const char *str2 = *ptr2;
return strcmp(str1, str2);
}
Upvotes: 1
Views: 161
Reputation: 1675
Just take a look at the return value of applying strcmp
directly to argv
:
int main(int argc, char * argv[])
{
int ret;
ret = strcmp(argv[1], argv[2]);
if (ret == 0)
printf("Equal strings.\n");
return 0;
}
By the way, if you're looking to have a function with generic arguments that compares two strings (i.e. to use in qsort()
), here's how you could go about it:
int string_cmp(const void * a, const void * b)
{
return strcmp((const char*)a, (const char*)b);
}
Upvotes: 5