Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!ucbvax!hplabs!hpda!hpwala!hpavla!gary From: gary@hpavla.AVO.HP.COM (Gary Jackoway) Newsgroups: comp.lang.c Subject: Re: Different Pointer Types Message-ID: <9130006@hpavla.AVO.HP.COM> Date: 8 Mar 90 14:16:16 GMT References: <31530004@hpcvia.CV.HP.COM> Organization: Hewlett-Packard Avondale Division Lines: 46 > / hpavla:comp.lang.c / brianh@hpcvia.CV.HP.COM (brian_helterline) I have a question about the following code. Given a structure like: > > struct FOO { > int type_of_data; > int number_of_elements; > union { > int *int_ptr; > unsigned int *un_int_ptr; > long *long_ptr; > } ptr; > }; >... > case 2 : /* long data */ > data_ptr = (char *) foo.ptr.long_ptr; > element_size = sizeof( long ); > break; > > for( i=0; i { > sum += (double) *data_ptr; > data_ptr += element_size; > } > 1) Is the above code ok? (other that typos which I've missed.) No, this will not work. The problem is that data_ptr is a char *. That means when you say (double) *data_ptr, you will double the byte length value at the location data_ptr points to. So whether you had an int, unsigned int or long, you would only sum the first byte of each data field. Instead you will need to have some caseing mechanism within the loop. Personally I'd say: switch (foo.type_of_data) case 0: for (i=0, iptr = foo.ptr.int_ptr; i