Different Pointer Types

brian_helterline brianh at hpcvia.CV.HP.COM
Wed Mar 7 02:16:38 AEST 1990


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;
	};

And a fuction to sum up the elements:

double sum( struct FOO foo )
{
    int i; element_size;
    long sum = 0L;
    char *data_ptr;

    switch ( foo.type_of_data ) {

      case 0 : 		/* integer data */
	data_ptr = (char *) foo.ptr.int_ptr;
	element_size = sizeof( int );
	break;

      case 1 :		/* unsigned data */
	data_ptr = (char *) foo.ptr.un_int_ptr;
	element_size = sizeof( unsigned int );
	break;

      case 2 :		/* long data */
	data_ptr = (char *) foo.ptr.long_ptr;
	element_size = sizeof( long );
	break;

      default :
	abort_with_error();
    }

    for( i=0; i<foo.number_of_elements; i++)
    {
	sum += (double) *data_ptr;
	data_ptr += element_size;
    }

    return( sum );
}


Here are my questions:

1) Is the above code ok? (other that typos which I've missed.)

2) Is this the best way to handle different types of pointers?  I realize
	that the above code depends on sizof( char ) == 1.  What is a
	better way?  I am stuck with the struct *AS IS*.

Thanks for any/all help/advice



More information about the Comp.lang.c mailing list