Article View: comp.lang.c.moderated
Article #2434Re: void* type
From: J. Kanze
Date: Sat, 30 Mar 1996 04:00
Date: Sat, 30 Mar 1996 04:00
68 lines
2459 bytes
2459 bytes
In article <4jckqc$a5o@solutions.solon.com> watzka@stat.uni-muenchen.de
(Kurt Watzka) writes:
|> If this is not the case, you cannot write such a function using pointers
|> to pointers. You can still write a generic swap(), but it takes two
|> void pointers as it's arguments, and it has an additional "size"
|> parameter. Such a generic swap function can fail, and it can be used
|> to swap two pointers to SomeType:
|> #include <string.h>
|> int
|> swap(void *a, void *b, size_t sz)
|> {
|> void *tmp;
|> tmp = malloc(sz);
|> if (tmp == NULL)
|> return 0;
|> memcpy(tmp, a, sz);
|> memcpy(a, b, sz);
|> memcpy(b, tmp, sz);
I think you forgot:
free( tmp ) ;
Otherwise, you are guaranteed that the function will return 0 if you
call it often enough:-).
|> return 1;
|> }
|> SomeType *a, b;
|> if (!swap(&a, &b))
|> /* die whining */
And you forgot your own extra parameter:-):
if ( ! swap( &a , &b , sizeof( SomeType ) )
...
BTW, I've found that a small optimizing trick in functions like this can
sometimes work wonders for performance:
int
swap( void* a , void* b , size_t sz )
{
unsigned char buffer[ EXPECTEDMAXSIZE ] ;
void* tmp = (sz <= sizeof( buffer ))
? buffer
: malloc( sz ) ;
if ( tmp == NULL )
return 0 ;
memcpy(tmp, a, sz);
memcpy(a, b, sz);
memcpy(b, tmp, sz);
if ( tmp != buffer )
free( tmp ) ;
return 1 ;
}
--
James Kanze (+33) 88 14 49 00 email: kanze@gabi-soft.fr
GABI Software, Sarl., 8 rue des Francs Bourgeois, 67000 Strasbourg, France
Conseils en informatique industrielle --
-- Beratung in industrieller Datenverarbeitung
Technical Details
Message-ID:
<4jibl5$89u@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4iepre$ag7@solutions.solon.com> <4ii34g$nlp@solutions.solon.com> <4ja3qf$p9b@solutions.solon.com> <4jckqc$a5o@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail
From: kanze@gabi-soft.fr (J. Kanze)
Newsgroups: comp.lang.c.moderated
Subject: Re: void* type
Date: 29 Mar 1996 22:00:37 -0600
Organization: GABI Software, Sarl.
Sender: clc@solutions.solon.com
Approved: clc@solutions.solon.com
Message-ID: <4jibl5$89u@solutions.solon.com>
References: <4iepre$ag7@solutions.solon.com> <4ii34g$nlp@solutions.solon.com>
<4ja3qf$p9b@solutions.solon.com> <4jckqc$a5o@solutions.solon.com>
NNTP-Posting-Host: solutions.solon.com