I’d like to implement search using C generics
int lsearchGeneric(void *key, void *base, int n, int elemSize)
{
int i =0;
for(; i < n; i++) {
void *elemAddr = (char*) base + i * elemSize;
if(memcmp(key, elemAddr , elemSize) == 0) {
return i;
}
}
return -1;
}
This function is called with
char *key = strdup("w");
char *base = strdup("two");
int result = lsearchGeneric (&key, base, 3, sizeof(char));
printf("Position: %d\n", result); // prints -1
I wonder what am i missing here. Instead of -1, i would expect 1, as “w” is the second letter in “two”
For those (you know who you are) who wonder whether this is homework – the answer is “no it is not. I am following Programming paradigms lecture from iTunesU”
Looks like you have an extra
&in your function call:You’re passing the address of the pointer rather than the pointer itself. The giveaway here is that you weren’t consistent with the two operands: You passed
&keyandbase, one with and the other without the&.Small Note:
This “generic” might not work properly with structs that have padding. As the padding values are unspecified and may be different with otherwise identical structs.