Re: [Dev-C++] Lookup tables, with bsearch, lsearch, qsort etc.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2003-01-16 16:04:31
|
Correction about strncpy
strncpy(PaperTypes.PaperStrings,"Letter",42-1);
PaperTypes.PaperStrings[42-1] = '\0';
strncpy will not insert a null-termination in case the string gets
clipped.
However, in this case, I assume that the goal was an array of 42 strings,
and not one string of max 42-1 characters.
char *PaperTypes[42];
and in that case it's allowed to do
PaperTypes[0] = "Letter";
PaperTypes[1] = "Legal";
PaperTypes[2] = "A4";
...
Normally then, You would do:
// Number of elements of a static array.
#define NELEM(a) (sizeof(a)/sizeof(*(a)))
struct Format {
int id,
const char *name;
} formats[] = {
{1,"Letter"},
{2,"Legal"},
{3,"A4"}
};
int cmp(const void *a,const void *b) {
const Format *pa = (const Format*)a;
const Format *pb = (const Format*)b;
return pa->id - pb->id;
}
int locate(const void *a,const void *b) {
int key = *(const int*)a;
const Format *fmt = (const Format*)b;
return key - fmt->id;
}
qsort(formats,NELEM(formats),sizeof(*formats),cmp);
int key = 2;
Format *p = bsearch(&key,formats,NELEM(formats),sizeof(*formats),locate);
/Per W
On Thu, 16 Jan 2003, Ioannis Vranos wrote:
> -------Original Message-------
>
> From: Daniel Glenfield
> Date: Thursday, 16 January 2003 11:09:47 AM
> To: pw...@ia...
> Cc: dev...@li...
> Subject: Re: [Dev-C++] Lookup tables, with bsearch, lsearch, qsort etc.
>
> Thanks I'll do some research.
> Can you tell me how to put these values in to a struct?
>
> 1, "Letter"
> 2, "Letter(small)"
> 3, "Tabloid"
>
> etc. I'm having trouble with this.
>
> // I asssume C
>
> ==> #include <string.h>
>
>
> struct PAPER
> {
> int Num;
> char* PaperStrings[42][1];
>
> ==>The 1 thing is reduntant!
>
> ==> char *PaperStrings[42];
>
>
> } PaperTypes, *PaperStruct = &PaperTypes;
>
> PaperTypes.Num = 1;
>
> PaperTypes.PaperStrings[42][1] = "Letter";
>
>
> ==> strncpy(PaperTypes.PaperStrings, "Letter", 42);
>
>
> PaperStruct->PaperStrings[40][1] = "Letter(small)";
>
> ==> /* ... */
>
> As you can see this is very wrong. I feel an idiot, but all the examples of
> structs I have seen do not use arrays or do anything like this, so I don't
> know how to do it!
>
>
>
> ==> I also suggest "The C Programming Language" 2nd Edition by Brian
> Kernighan - Dennis Ritchie (the creator of C).
>
>
> Ioannis Vranos
>
> * Programming pages: http://www.noicys.freeurl.com
> * Alternative URL: http://run.to/noicys
|