Ramprasad said:
Dan Pop wrote:
Ok I have put the email ids in a sorted array.
Can I use bsearch on an array with differrent sized elements. Because in
a real scenario the email ids will have different sizes
No bsearch and qsort is not suitable for different sized elements.
However you can use an array of char pointers and use
qsort to sort the array of char pointers and use bsearch to find the key
in the array.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct EMAILLIST
{
char **email;
size_t email_count;
} EMAILLIST;
int AddEmailAddr(const char *s, EMAILLIST *p);
char **SearchEmailList(const char *key, EMAILLIST *p);
void FreeEmailList(EMAILLIST *p);
int cmp(const void *v1, const void *v2);
int main(void)
{
EMAILLIST my = {NULL};
char **tmp, *s;
char emails[] = "<
[email protected]> <
[email protected]> "
"<
[email protected]> <
[email protected]>";
s = strtok(emails," ");
while(s)
{
AddEmailAddr(s,&my);
s = strtok(NULL," ");
}
AddEmailAddr("<
[email protected]>",&my);
if((tmp = SearchEmailList("<
[email protected]>",&my)) != NULL)
printf("Email \"%s\" found in the list\n",*tmp);
printf("TEST: my.email_count = %u\n",my.email_count);
FreeEmailList(&my);
return 0;
}
int AddEmailAddr(const char *s, EMAILLIST *p)
{
char **tmp;
size_t num = p->email_count;
if(p->email != NULL)
if(SearchEmailList(s,p) != NULL)
{
printf("Email Dupe, Email \"%s\" not added\n",s);
return 0;
}
if((tmp = realloc(p->email,
(num+1)*(sizeof *p->email))) == NULL)
{
printf("Memory Allocation Error, Email \"%s\" not added\n",s);
return 0;
}
p->email = tmp;
if((p->email[num] = malloc(strlen(s)+1)) == NULL)
{
printf("Memory Allocation Error, Email \"%s\" not added\n",s);
return 0;
}
strcpy(p->email[num],s);
qsort(p->email,++p->email_count,sizeof *p->email,cmp);
return 1;
}
void FreeEmailList(EMAILLIST *p)
{
size_t i;
for(i = 0;i < p->email_count;i++)
free(p->email
);
free(p->email);
p->email = NULL;
p->email_count = 0;
return;
}
int cmp(const void *v1, const void *v2)
{
const char **s1 = (const char **)v1;
const char **s2 = (const char **)v2;
return strcmp(*s1,*s2);
}
char **SearchEmailList(const char *key, EMAILLIST *p)
{
if(p->email == NULL) return NULL;
return bsearch(&key,p->email,p->email_count,sizeof(char *),cmp);
}