[英]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.我正在尝试解决以下问题:编写代码,使用 void 指针检查整数或 c 字符串数组是否包含彼此相邻的两个相同项。 The method that compares integers works but the code for c-strings crashes.
比较整数的方法有效,但 c 字符串的代码崩溃。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.