に、私は次のプログラムがありますBSEARCHとジャンク値比較関数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#define DICT_BUFSIZE 64
int compar(const void * a, const void * b)
{
const char* c1 = (const char*)a;
const char* c2 = (const char*)b;
printf("c1: %s | c2: %s\n", c1, c2);
return strcmp(c1, c2);
}
int main (void)
{
FILE* fdict;
uint32_t i;
char** dict = NULL;
size_t size = 0;
size_t size_alloced = 0;
char buf[DICT_BUFSIZE];
fdict = fopen("/usr/share/dict/words", "r");
if (!fdict) {
printf("Could not open \"%s\": %s\n", "usr/share/dict/words", strerror(errno));
exit(1);
}
for (i = 0; fgets(buf, DICT_BUFSIZE, fdict); ++i) {
size_t len;
if (i == size_alloced) {
dict = realloc(dict, (i +50000) * sizeof(*dict));
size_alloced += 50000;
}
len = strlen(buf);
dict[i] = malloc(len);
memcpy(dict[i], buf, len -1);
dict[i][len -1] = '\0';
}
size = i;
//for (i = 0; i < size; i++)
//printf("%s\n", dict[i]);
if(bsearch("company", dict, size, sizeof(*dict), compar))
printf("Found!\n");
for (i = 0; i < size; ++i)
free(dict[i]);
free(dict);
fclose(fdict);
return 0;
}
「C1」の変数(検索されるキー)が正しく表示されている「比較例」機能では、しかし、ジャンク出力がありますv2変数に格納されます。
は、ここでの出力例です:
c1: company | c2: ���
c1: company | c2: �$z
c1: company | c2: ��I
c1: company | c2: ��7
c1: company | c2: P�.
c1: company | c2: �b3
c1: company | c2: �1
c1: company | c2: P�/
c1: company | c2: ��0
c1: company | c2: PC0
c1: company | c2: @g0
c1: company | c2: y0
c1: company | c2: 0�0
c1: company | c2: ��0
c1: company | c2: `�0
c1: company | c2: ��0
c1: company | c2:
c1: company | c2: P�0
私は、この動作を理解することはできません。
私ははsizeof(* dictのは)あなたはそれがないと思う値を持っているとは思いません。 – Irisshpunk
私はすぐにそれを犯人と考えましたが、何が間違っているのか見当たりません。 – Nick