简体   繁体   中英

How do I use strcmp with void pointers

I'm trying to solve the following question: Write code that checks if an array of ints or c-strings contains two identical items next to each other using void pointers. The method that compares integers works but the code for c-strings crashes. I couldn't find anything that indicates what the problem is. Sorry if there's any mistakes this is translated from Dutch.

#include <stdio.h>
#include <string.h>

int array_contains_sequential_doubles(const void* t, int length, int size, int (*compare)(const void* a, const void* b))
{
    const char* p = (const char*)t;
    int i = 1;
    p += size;
    while (i < length) {
        if (compare(p - size, p))
            return 1;
        i++;
        p += size;
    }
    return 0;
}

int compare_int(const void* a, const void* b)
{
    int ia = *((const int*)a);
    int ib = *((const int*)b);
    //printf("%d en %d\n", ia, ib);
    return ia == ib;
}

int compare_string(const void* a, const void* b)
{
    const char** sa = (const char**)a;
    const char** sb = (const char**)b;
    return strcmp(*sa, *sb) == 0;
}

int main()
{
    int numbers_ja[] = { 3, 2, 1 };
    int numbers_neen[] = { 1, 2, 2, 1 };
    char* woorden_ja[] = { "this", "is", "is", "a", "test" };
    char* woorden_neen[] = { "this", "is", "fine" };

    int i = array_contains_sequential_doubles(numbers_ja, sizeof(numbers_ja) / sizeof(int), sizeof(int), compare_int);
    printf("%d\n", i);

    i = array_contains_sequential_doubles(numbers_neen, sizeof(numbers_neen) / sizeof(int), sizeof(int), compare_int);
    printf("%d\n", i);

    i = array_contains_sequential_doubles(numbers_ja, sizeof(woorden_ja) / sizeof(const char*), sizeof(const char*), compare_string);
    printf("%d\n", i);

    i = array_contains_sequential_doubles(numbers_neen, sizeof(woorden_neen) / sizeof(const char*), sizeof(const char*), compare_string);
    printf("%d\n", i);

    return 0;
}

Shouldn't this been written as woorden instead of numbers ?

i = array_contains_sequential_doubles(woorden_ja, sizeof(woorden_ja) / sizeof(const char*), sizeof(const char*), compare_string);
printf("%d\n", i);

i = array_contains_sequential_doubles(woorden_neen, sizeof(woorden_neen) / sizeof(const char*), sizeof(const char*), compare_string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM