Andreas - 1 month ago 15
C Question

# Where is the mistake in my program? (sorting by age)

I'm trying to sort people by their age but somehow the months and the years are overwritten with the value from some other person. I already tried finding the mistake but wasn't successful.

``````void sortPersonsByAge(struct person *first, int cnt) {
int i, j;
struct person *oldest = first;

for (j = 0; j < cnt-1; j++)
{
oldest = first + j;
for (i = j; i < cnt; i++)
{
struct person *person = first + i;
if (person->year_of_birth < oldest->year_of_birth)
oldest = person; // es gibt einen neuen Altersrekord
else if (person->year_of_birth = oldest->year_of_birth)
// in this else if is the mistake somewhere
{
if (person->month_of_birth < oldest->month_of_birth)
oldest = person;
else if (person->month_of_birth = oldest->month_of_birth)
if (person->day_of_birth < oldest->day_of_birth)
oldest = person;
}
}
// let's swap the first person with the oldest person

struct person tmp; // Zwischenspeicher
tmp = *(first+j);
*(first+j) = *oldest;
*oldest = tmp;
}
}
``````

``````    else if (person->year_of_birth = oldest->year_of_birth)
are always true (supposing `oldest->year_of_birth` and `oldest->month_of_birth` are not zero) as the value of assignment operator `=` is the value of its right-side.
You probably wanted operator of comparison, which is `==` (double `=`).