Re: [Dev-C++] Lookup tables, with bsearch, lsearch, qsort etc.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Ioannis V. <no...@ho...> - 2003-01-16 19:08:19
|
-------Original Message-------=0D
=0D
From: Per Westermark=0D
Date: Thursday, 16 January 2003 6:03:21 PM=0D
To: Ioannis Vranos=0D
Cc: dev...@li...=0D
Subject: Re: [Dev-C++] Lookup tables, with bsearch, lsearch, qsort etc.=0D
=0D
Correction about strncpy=0D
strncpy(PaperTypes.PaperStrings,"Letter",42-1);=0D
PaperTypes.PaperStrings[42-1] =3D '\0';=0D
=0D
strncpy will not insert a null-termination in case the string gets=0D
clipped.=0D
=0D
However, in this case, I assume that the goal was an array of 42 strings,=
=0D
and not one string of max 42-1 characters.=0D
=0D
char *PaperTypes[42];=0D
=0D
and in that case it's allowed to do=0D
=0D
PaperTypes[0] =3D "Letter";=0D
PaperTypes[1] =3D "Legal";=0D
PaperTypes[2] =3D "A4";=0D
=2E..=0D
=0D
Normally then, You would do:=0D
=0D
// Number of elements of a static array.=0D
#define NELEM(a) (sizeof(a)/sizeof(*(a)))=0D
=0D
struct Format {=0D
int id,=0D
const char *name;=0D
} formats[] =3D {=0D
{1,"Letter"},=0D
{2,"Legal"},=0D
{3,"A4"}=0D
};=0D
=0D
=0D
int cmp(const void *a,const void *b) {=0D
const Format *pa =3D (const Format*)a;=0D
const Format *pb =3D (const Format*)b;=0D
=0D
return pa->id - pb->id;=0D
}=0D
=0D
int locate(const void *a,const void *b) {=0D
int key =3D *(const int*)a;=0D
const Format *fmt =3D (const Format*)b;=0D
=0D
return key - fmt->id;=0D
}=0D
=0D
qsort(formats,NELEM(formats),sizeof(*formats),cmp);=0D
=0D
int key =3D 2;=0D
Format *p =3D bsearch(&key,formats,NELEM(formats),sizeof(*formats),locate=
);=0D
=0D
/Per W=0D
=0D
=0D
=3D=3D> Yes, you are right. Probably i had my mind to something else at t=
he time
:) I used a char *array as a char array, etc.=0D
=0D
=0D
Ioannis Vranos=0D
=0D
* Programming pages: http://www.noicys.freeurl.com=0D
* Alternative URL: http://run.to/noicys=20 |