James Raitsev
James Raitsev

Reputation: 96461

On C and generic functions

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"

Upvotes: 3

Views: 168

Answers (2)

Mysticial
Mysticial

Reputation: 471369

Looks like you have an extra & in your function call:

int result = lsearchGeneric (&key, base, 3, sizeof(char));
                             ^
                        does not belong here!

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 &key and base, 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.

Upvotes: 4

Brooks Moses
Brooks Moses

Reputation: 9527

If you step through this in a debugger, the first thing you'll notice is that the value of "key" inside the function isn't "w" -- instead, it's some garbage. If you look closer, you'll notice that the address isn't the same as when you checked it out in the main program, either.

The reason for this is that you are calling your function with the address of the pointer of the key value -- &key -- rather than the address of the key value itself, which is key. Remove the extraneous &, and it works right.

Upvotes: 2

Related Questions