pabloliva87

Ej3C

Mar 20th, 2012
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.14 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. #define offsetof(structure, field) (size_t)(&((structure*)0)->field)
  5.  
  6. struct person_struct
  7. {
  8.     float height;
  9.     int age;
  10.     float weight;
  11. }; 
  12.  
  13. typedef struct person_struct person;
  14.  
  15. int sumar(const void* arreglo, size_t tamanio_elemento, size_t offset_campo, size_t cant_elementos);
  16.  
  17. int main (void)
  18. {
  19.     int i;
  20.     int result;
  21.     person ppl_list[10];
  22.  
  23.     for (i=0; i<10; i++)
  24.     {
  25.         ppl_list[i].height = 1.4 + i/10.;
  26.         ppl_list[i].age = 15 + i;
  27.         ppl_list[i].weight = 50. + 2.* i;
  28.     }
  29.    
  30.     result = sumar(&ppl_list[0],sizeof(person), offsetof(person, age), sizeof(ppl_list)/ sizeof(ppl_list[0]));
  31.     printf("El resultado es: %i\n", result);
  32.  
  33.     return EXIT_SUCCESS;
  34. }
  35.  
  36. int sumar(const void* arreglo, size_t tamanio_elemento, size_t offset_campo, size_t cant_elementos)
  37. {
  38.     int result, i, current_value;
  39.     char * pointer_to_element;
  40.    
  41.     result = 0;
  42.    
  43.     pointer_to_element = (char*) arreglo;
  44.     pointer_to_element += offset_campo;
  45.    
  46.     for (i=0; i<cant_elementos; ++i)
  47.     {
  48.         current_value = *(int*) pointer_to_element;
  49.         result += current_value;
  50.         pointer_to_element += tamanio_elemento;
  51.     }
  52.     return result;
  53. }
Add Comment
Please, Sign In to add comment