It is good that you posted your code in code tags and with some attempt at indentation. However, it would be even better to use more than one space per indent level, to separate parts of your code with blank lines, and to be a little more consistent. For example:
Code:
#include <stdio.h>
struct person
{
char first_name[20];
char last_name[20];
int age;
};
void print_person_info(struct person info);
void sort_age(int n, struct person peeps[]);
int main()
{
int i, n = 5;
struct person student[5] =
{
{"Bob", "Smith", 21},
{"Jim", "Smith", 13},
{"Amy", "Smith", 19},
{"Tam", "Smith", 24},
{"Sally", "Smith", 17}
};
for (i = 0; i < n; i++)
{
print_person_info(student[i]);
}
sort_by_age(5, student);
/*printf("----After Sorting------\n");
for (i=0; i < n; i++)
[I] print_person_info(student);*/
}
void print_person_info(struct person info)
{
printf("Name = %s %s\n", info.first_name, info.last_name);
printf("Age = %i\n\n", info.age);
}
void sort_age(int n, struct person peeps[])
{
printf("n = %i %s %s %i", n , peeps[1].first_name, peeps[1].last_name, peeps[1].age);
}
I suggest:
Code:
struct person student[] =
{
{"Bob", "Smith", 21},
{"Jim", "Smith", 13},
{"Amy", "Smith", 19},
{"Tam", "Smith", 24},
{"Sally", "Smith", 17}
};
const size_t n = sizeof(student) / sizeof(student[0]);
This way, you can add or remove entries from the initialiser without worrying about forgetting to change the "5" or the initialiser for n. I changed n to be a size_t because size_t is the type of the result of sizeof, and besides, it is non-negative. You should change the declaration of i to match.
You probably do not want to copy the struct person object for printing, so you should pass a pointer to it:
Code:
void print_person_info(const struct person *info)
{
printf("Name = %s %s\n", info->first_name, info->last_name);
printf("Age = %i\n\n", info->age);
}
I used the const keyword since within the context of this function, the struct person object is effectively constant: you have no need to modify it to print its contents.
Likewise, you could create another function for printing the entire list of persons:
Code:
void print_persons(const struct person persons[], size_t n)
{
size_t i;
for (i = 0; i < n; i++)
{
print_person_info(&persons[i]);
}
}
This way, you avoid duplicating code for printing the list before and after the sort.
Originally Posted by
screwlu
I'm trying to make function that sort the structure by youngest to oldest, but I'm having a problem with the function it self and the test inside of it. When I try to compile it, I get a reference error.
What exactly is the error message?