1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

struct: dynamic user input

Discussion in 'C' started by pako, Aug 24, 2012.

  1. pako

    pako New Member

    Joined:
    Aug 21, 2012
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Could you please show me how to change from static(below) to dynamically input data from the user, store it in struct and qsort it;
    Code:
    ...
    ...
    struct olympics { 
        char fname[15];
        char fname[15];
        char country[5];
        float time;
    }; 
    ...
    ....
    void print_struct_array(struct olympics *array, size_t len) 
    { 
        size_t i;
     
        for(i=0; i<len; i++) 
            //printf("\n[ athlete: %s \t time: $%.2f ]\n", array[i].athlete, array[i].time);
    	printf("%s %s \t %.2f\n", array[i].athlete, array[i].country, array[i].time);
     
        puts("****");
    } 
     
    /* sorting structs using qsort() example */ 
    void sort_structs_time(void) 
    { 
        struct olympics structs[] = {
    		{"STENA John\t\t","FRA", 405.95f}, 
    		{"PARKER Paul\t","GB", 403.01f},
    		{"WHITE Lauren\t\t","NZL", 406.25f}, 
    		{"BRUTTH Camille\t\t","FRA", 401.45f}, 
    		{"BROWN Lewis\t","ITA", 404.50f}, 
    		{"TURNER Mike\t\t","DNK", 403.98f }
    	};
     
        size_t structs_len = sizeof(structs) / sizeof(struct olympics);
     
        puts("**** Athletes finishing time...");
     
        /* print original struct array */ 
        print_struct_array(structs, structs_len);
     
        /* sort array using qsort functions */ 
        qsort(structs, structs_len, sizeof(struct olympics), struct_cmp_by_time);
     
        /* print sorted struct array */ 
        print_struct_array(structs, structs_len);
    ...
    ....
     
  2. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    // if declared in the same scope
    
    struct olympics *dynamic = malloc(sizeof(*dynamic) * number_of_elements);
    or 
    struct olympics *dynamic = calloc(number_of_elements, sizeof(*dynamic));
    
    // if declared elsewhere
    
    dynamic = malloc(sizeof(olypmics) * number_of_elements);
    or
    dynamic = calloc(number_of_elements, sizeof(olympics));
    
    
    if(dynamic) {   
       dynamic[index].field_name = some value
       (dynamic + index)->field_name = some value
    }
    
    qsort(dynamic, elements, sizeof(olympics), compare_function);
    
    do something with sorted list
    
    free(dynamic);
    
     

Share This Page