I got a strange error while compiling this code. Its the same as in the book im studying from, but it seems it gets confused somewhere, because my output is off, ages and names got mixed eg( darko 4, zdendk 3, matija 2, draga(dont know where the "n" is gone) 1) and it says invalid pointer. Help me to understand why this is happening.
#include <iostream>
#include <math.h>
#include <cstdlib>
//#include "Tablica.h"
using namespace std;
/*
*
*/
struct Person {
string name;
int age;
};
int compare (const void* a, const void* b){
const Person* p1 = static_cast<const Person*>(a);
const Person* p2 = static_cast<const Person*>(b);
if(p1->age != p2->age)
return p2->age - p1->age;
return p1->name.compare(p2->name);
}
int main(int argc, char** argv) {
Person people[]{{"darko", 1},{"zdendka", 2},{"matija", 3},{"dragan", 4}};
int numP = sizeof(people) / sizeof(Person);
qsort(people, numP, sizeof(Person), compare);
for(Person x:people){
cout<< x.name <<" "<<x.age<<endl;
}
return 0;
}