Re: ECPG - how to fetch then sort strings

From: Poul Jensen <flyvholm(at)gfy(dot)ku(dot)dk>
To: Martijn van Oosterhout <kleptog(at)svana(dot)org>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: ECPG - how to fetch then sort strings
Date: 2006-09-09 12:09:43
Message-ID: 4502AF07.4050406@gfy.ku.dk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Martijn van Oosterhout wrote:
> Please don't use "reply" to start new thread, thanks.
>
> On Fri, Sep 08, 2006 at 05:55:44AM -0800, Poul Jensen wrote:
>
>> I need to fetch strings from a database with ECPG and then sort them in
>> C. Here is one of my failed attempts:
>>
>
> <snip>
>
>> varchar filenms[][maxlen]=NULL;
>>
>
> I think you need to reread the C manual as to the difference between
> arrays and pointers. I'm don't know about ECPG, but I think your other
> attempt, using "char**" was much closer to the mark.
>
>
>> It compiles ok, but I get garbage in variable filenms. If I change the
>> declaration of filenms to:
>> char **filenms=NULL;
>> the SQL query returns strings ok. But the strings have variable length,
>> and I need to specify one length in qsort, so it won't work. Another
>>
>
> Since you're declaring a array of pointers to char, the width you have
> to specify to qsort would be sizeof(char*). I think you can just use
> the normal strcmp() function with qsort then.
>
> Ofcourse, you could get the database to sort them for you...
>
> Hope this helps,
>
I'm afraid it didn't for various reasons, but I appreciate you trying.
What I ended up doing was simply declaring an extra array outside the
SQL declare section:

char (*tmp)[maxlen];

Then allocate the required memory once known:

if (( tmp = malloc(maxlen*nrec*sizeof(char)) ) == NULL) {
fprintf(stderr,"Memory allocation failure\n");
exit(-1);
}

and then just copy the strings into it one by one. As for strcmp it
*can* be used directly in qsort, but not without some manipulation:

qsort(tmp, nrec, maxlen*sizeof(char), (int(*)(const void*, const
void*))&strcmp);

This resolved my issues. For now. ;-)

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Marc G. Fournier 2006-09-09 15:50:36 Re: Majordomo drops multi-line Subject:
Previous Message Martijn van Oosterhout 2006-09-09 12:06:13 Re: [GENERAL] Problem with lo_export() and lo_import() from remote machine.