I am learning c++. I got a struct array that has an attribute that is also a struct.
typedef struct Date
{
int day, month, year;
}Date;
typedef struct {
int order_num;
Date order_day; //Sort
string client;
string tech_type;
int serial_key;
char problem[50];
string technician_name;
char tech_fix[500];
int price;
int days_spent;
string status;
string order_type;
string urgency;
int problems_num;
faults problems[10];
}tech_info;
The question is that I need to sort it via date, that is the second attribute on tech_info.
Here is my attempt:
bool compare_date(const tech_info *a, const tech_info *b)
{
if (a->order_day.year < b->order_day.year)
return true;
if (a->order_day.year == b->order_day.year &&
a->order_day.month < b->order_day.month)
return true;
if (a->order_day.year == b->order_day.year &&
a->order_day.month == b->order_day.month &&
a->order_day.day < b->order_day.day)
return true;
// If none of the above cases satisfy, return false
return false;
}
static void sort_date(tech_info* all_orders[]) {
sort(all_orders, all_orders + counter, compare_date);
cout << "Sorted by date. " << "\n";
}
In this case counter is the amount of entries the user has submitted.
I submit two entries. For the first one I read the information correctly, but for the second one I don't. I'll attach two screenshots to show. Where is my mistake?
Update: Given that I am accessing bad memory I'll post a bit more of my code, all the parts that have to do with this logic. Here is where I declare my array:
print_menu_initial();
int user_input;
cin >> user_input;
tech_info* orders[100]; //Empty by default
switch (user_input) {
case 1:
do_work_technician_mode(orders);
break;
case 2:
do_work_customer_mode(orders);
break;
}
Then the user does some operations to add orders from here:
static void do_work_customer_mode(tech_info* all_orders[]) {
while (true) {
cin >> user_input;
switch (user_input) {
case 0:
do_work_technician_mode(all_orders);
break;
case 1:
order[counter] = add_order();
all_orders[counter] = &order[counter];
counter++;
break;
case 2:
cout << "How many orders would you like to add? ";
cin >> many_orders;
for (int i = 0; i < many_orders; i++) {
cout << "Information for next order: " << "\n";
order[counter + i] = add_order();
all_orders[counter + 1] = &order[counter + 1];
}
counter = counter + many_orders;
break;
case 6:
sort_date(all_orders);
break;
}
The other cases are irrelevant, I believe. This is the sorting part. Counter is an int variable, declared 0 at start. Whenever the customer adds new entries I increase the value of counter with the number of entries he adds.
Funny enough - for my screenshot - variable a gets read correctly, just b is not being read correctly.