Steph said:
Hello,
I have filled a dynamic array of strings (realloc() + malloc())
char **sMyArray;
At the end, I get correctly sMyArray[0] = "STRING_0", sMyArray[1] =
"STRING_1", etc...
But I'm unable to use bsearch(). It doens't find any string.
(and nSize = sizeof(sMyArray[0]) = 4,
which is not what I would want (8))
Is it possible ?
/* BEGIN new.c */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define KEY "STRING_8"
#define TEN {"STRING_0","STRING_1", \
"STRING_2","STRING_3","STRING_4","STRING_5", \
"STRING_6","STRING_7","STRING_8","STRING_9"}
#define NMEMB(A) (sizeof (A) / sizeof (*A))
int comparison(const void *, const void *);
void free_sMyArray(char **sMyArray, size_t nmemb);
int main(void)
{
char *ten[] = TEN;
char *key = KEY;
char **sMyArray;
char **found;
size_t index;
sMyArray = malloc(NMEMB(ten) * sizeof *sMyArray);
for (index = 0; index != NMEMB(ten); ++index) {
sMyArray[index] = malloc(sizeof "STRING_8");
if (sMyArray[index] == NULL) {
free_sMyArray(sMyArray, index);
puts("sMyArray[index] == NULL");
exit(EXIT_FAILURE);
}
}
qsort(ten, NMEMB(ten), sizeof *ten, comparison);
for (index = 0; index != NMEMB(ten); ++index) {
strcpy(sMyArray[index], ten[index]);
puts(sMyArray[index]);
}
putchar('\n');
printf("searching for %s\n", key);
found = bsearch
(&key, sMyArray, NMEMB(ten), sizeof *ten, comparison);
if (found == NULL) {
puts("found == NULL");
} else {
printf("found %s\n", *found);
}
free_sMyArray(sMyArray, NMEMB(ten));
return 0;
}
int comparison(const void *a, const void *b)
{
return strcmp(*(const char **)a, *(const char **)b);
}
void free_sMyArray(char **sMyArray, size_t nmemb)
{
while (nmemb-- != 0) {
free(sMyArray[nmemb]);
}
free(sMyArray);
}
/* END new.c */