This is a simple example of working with an array of structs. Instead of reading the data from a file, in this example, it's initialized into the array.
Code:
/*
*/
#include <stdio.h>
#define SIZE 5
typedef struct {
char name[30];
int points;
int level;
}player;
int main() {
int i, j, sorted;
player temp;
player p[SIZE]={
{"Alice",222, 4},
{"Tyler", 194, 5},
{"Chris", 190, 5},
{"Tom", 210, 6},
{"Mary", 208, 6}};
//sort the records, by ascending points
for(i=0; i<SIZE-1; i++)
{
for(j=i+1; j<SIZE; j++)
{
if(p[i].points > p[j].points)
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
//show the records:
printf("\nPlayer records, in sorted order: \n");
for(i=0;i<SIZE;i++) {
printf("%20s %3d %2d\n", p[i].name,p[i].points,p[i].level);
}
printf("\n\n\t\t press enter");
(void) getchar();
return 0;
}
Whiteflags posted:
Last but not least, lists might also be appropriate, because they aren't limited to a fixed number of elements, but they don't provide random access to elements in C.
< And are generally a righteous PITA! >