home *** CD-ROM | disk | FTP | other *** search
- 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
- From: spt@sgtech.sgtech.com (Steve Thorn)
- Newsgroups: comp.lang.c
- Subject: overlaying variables: the right way?
- Message-ID: <9207281358.AA15617@sgtech.sgtech.com>
- Date: 28 Jul 92 13:58:23 GMT
- Sender: daemon@ucbvax.BERKELEY.EDU
- Lines: 49
-
-
- Someone asked me the other day how to write a function that is passed a string
- and a 'type' integer, and return a value in a known memory location which is
- of the 'type' asked for. eg. convert(&string, type, &value_buffer). This is
- what I came up with, and I'm wondering if there's a better/prettier way.
-
- #define INT_T 0
- #define CHAR_T 1
- #define STRING_T 2
-
- void convert(string, type, value_buffer)
- char *string;
- char type;
- void *value_buffer;
- {
- switch (type) {
- case INT_T:
- sscanf(string, "%d", value_buffer);
- break;
- case CHAR_T:
- sscanf(string, "%c", value_buffer);
- break;
- default:
- case STRING_T:
- strcpy(value_buffer, string);
- break;
- }
- }
-
- void main()
- {
- char value[256];
-
- convert("34.56", INT_T, value);
- printf("Integer is %d\n", *(int *)value);
- convert("34.56", CHAR_T, value);
- printf("Char is %c\n", *(char *)value);
- convert("34.56", STRING_T, value);
- printf("String is %s\n", value);
- }
-
- Any ideas?
-
- -steve
-
-
- Steve Thorn spt@sgtech.com
- Star Gate Technologies, Inc. ...!uunet!abvax!sgtech!spt
- 29300 Aurora Rd, Solon, OH 44139 216-349-1860
-