Menu
Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
Functions taking pointers to different types as arguments
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
<blockquote data-quote="Chris Torek" data-source="post: 2398169"><p>The problem is isomorphic to:</p><p></p><p> "What kind of pointer should I use to point to either a char</p><p> or a double, so that I can write *p = 3 to set the char to</p><p> control-C or the double to 3.0?"</p><p></p><p>The answer is: there is no such pointer. You must change the</p><p>problem.</p><p></p><p>In this case, the solution to the problem is to write a wrapper</p><p>function. Since we know "void *" is a general-purpose data</p><p>pointer, write a wrapper for fgetc():</p><p></p><p> int wrap_fgetc(void *vp) {</p><p> FILE *fp = vp;</p><p></p><p> return fgetc(fp);</p><p> }</p><p></p><p>Assuming gzgetc() has type "int gzgetc(void *)", you now have two</p><p>"int (void *)" functions, and can point to either one with:</p><p></p><p> int (*fp)(void *) = straight ? wrap_fgetc : gzgetc;</p><p></p><p>Of course, you must also convert the argument as well:</p><p></p><p> void *arg = straight ? the_fgetc_file : the_gzgetc_voidstar;</p><p></p><p>If your second function (gzgetc, here) had some other pointer</p><p>type as its sole parameter, you could wrap both functions, because</p><p>"void *" will always be able to hold any other pointer.</p></blockquote><p></p>
[QUOTE="Chris Torek, post: 2398169"] The problem is isomorphic to: "What kind of pointer should I use to point to either a char or a double, so that I can write *p = 3 to set the char to control-C or the double to 3.0?" The answer is: there is no such pointer. You must change the problem. In this case, the solution to the problem is to write a wrapper function. Since we know "void *" is a general-purpose data pointer, write a wrapper for fgetc(): int wrap_fgetc(void *vp) { FILE *fp = vp; return fgetc(fp); } Assuming gzgetc() has type "int gzgetc(void *)", you now have two "int (void *)" functions, and can point to either one with: int (*fp)(void *) = straight ? wrap_fgetc : gzgetc; Of course, you must also convert the argument as well: void *arg = straight ? the_fgetc_file : the_gzgetc_voidstar; If your second function (gzgetc, here) had some other pointer type as its sole parameter, you could wrap both functions, because "void *" will always be able to hold any other pointer. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Functions taking pointers to different types as arguments
Top