Different Pointer Types

Gary Jackoway gary at hpavla.AVO.HP.COM
Fri Mar 9 00:16:16 AEST 1990


> / hpavla:comp.lang.c / brianh at 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<foo.number_of_elements; 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<foo.number_of_elements;
		++i, ++iptr)
		sum += *iptr;
	    break;
	case 1:
	...
and do this for each type of data with different pointers.  Note that
iptr must be sized correctly (int *iptr).  Then ++iptr is sufficient
without going through any element size contortions.

Gary Jackoway



More information about the Comp.lang.c mailing list