home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / c / 11665 < prev    next >
Encoding:
Text File  |  1992-07-28  |  1.5 KB  |  59 lines

  1. Path: sparky!uunet!europa.asd.contel.com!darwin.sura.net!mips!sdd.hp.com!uakari.primate.wisc.edu!ames!agate!ucbvax!sgtech.sgtech.com!spt
  2. From: spt@sgtech.sgtech.com (Steve Thorn)
  3. Newsgroups: comp.lang.c
  4. Subject: overlaying variables: the right way?
  5. Message-ID: <9207281358.AA15617@sgtech.sgtech.com>
  6. Date: 28 Jul 92 13:58:23 GMT
  7. Sender: daemon@ucbvax.BERKELEY.EDU
  8. Lines: 49
  9.  
  10.  
  11. Someone asked me the other day how to write a function that is passed a string
  12. and a 'type' integer, and return a value in a known memory location which is
  13. of the 'type' asked for.  eg. convert(&string, type, &value_buffer).  This is
  14. what I came up with, and I'm wondering if there's a better/prettier way.
  15.  
  16. #define INT_T    0
  17. #define CHAR_T   1
  18. #define STRING_T 2
  19.  
  20. void convert(string, type, value_buffer)
  21.   char *string;
  22.   char type;
  23.   void *value_buffer;
  24. {
  25.   switch (type) {
  26.     case INT_T:
  27.       sscanf(string, "%d", value_buffer);
  28.       break;
  29.     case CHAR_T:
  30.       sscanf(string, "%c", value_buffer);
  31.       break;
  32.     default:
  33.     case STRING_T:
  34.       strcpy(value_buffer, string);
  35.       break;
  36.   }
  37. }
  38.  
  39. void main()
  40. {
  41.   char value[256];
  42.  
  43.   convert("34.56", INT_T, value);
  44.   printf("Integer is %d\n", *(int *)value);
  45.   convert("34.56", CHAR_T, value);
  46.   printf("Char is %c\n", *(char *)value);
  47.   convert("34.56", STRING_T, value);
  48.   printf("String is %s\n", value);
  49. }
  50.  
  51. Any ideas?
  52.  
  53. -steve
  54.  
  55.  
  56. Steve Thorn                         spt@sgtech.com
  57. Star Gate Technologies, Inc.        ...!uunet!abvax!sgtech!spt
  58. 29300 Aurora Rd, Solon, OH  44139         216-349-1860
  59.