#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct train
{
int id;
int hours;
int minutes;
char destination[21];
};
// сравнивать поезда по каждому из параметров по возрастанию
// ввод: 2 указателя на 2 поезда
// возврат: больше 0, если поезд дальше в списке, меньше 0, если наоборот
int cmpTrains(void const *, void const *);
int cmpTrains(void const *voidTr1, void const *voidTr2)
{
int res;
struct train *tr1 = voidTr1;
struct train *tr2 = voidTr2;
if ((tr1->hours * 60 + tr1->minutes) -
(tr2->hours * 60 + tr2->minutes) != 0)
res = (tr1->hours * 60 + tr1->minutes) -
(tr2->hours * 60 + tr2->minutes);
else if (strcmp(tr1->destination, tr2->destination))
res = strcmp(tr1->destination, tr2->destination);
else res = tr1->id - tr2->id;
return res;
}
// Перевести строчку в вехний регистр
// Ввод: указатель на строчку
// Вывод: изменение строчки по указателю
void to_upper(char *);
void to_upper(char *str)
{
while (*str)
{
*str = toupper(*str);
str++;
}
return;
}
int main()
{
// N is amount of trains
int K, N;
struct train **ptrs = NULL;
scanf("%d%d", &K, &N);
// ptrs it is a pointer, that's reffering to other pointers to train objects.
ptrs = calloc(N, sizeof(struct train*));
for (int i = 0; i < N; i++)
{
ptrs[i] = (struct train *)malloc(sizeof(struct train));
scanf("%d %d:%d %s",
&ptrs[i]->id,
&ptrs[i]->hours,
&ptrs[i]->minutes,
ptrs[i]->destination);
to_upper(ptrs[i]->destination);
}
qsort((void *)ptrs, N, sizeof(struct train *), cmpTrains);
int cmp = 0, time;
printf("n");
for (int i = 0; i < K; i++)
{
time = ptrs[i]->hours * 60 + ptrs[i]->minutes;
printf("%03d %02d:%02d %s %dn", ptrs[i]->id, ptrs[i]->hours,
ptrs[i]->minutes, ptrs[i]->destination, time - cmp);
cmp = time;
}
for (int i = 0; i < N; i++)
free(ptrs[i]);
free(ptrs);
return 0;
}
Input in the console was:
4
6
124 12:02 habarovsk
13 12:02 VladiDMir
1 00:01 rOstov
101 23:05 MariuPl
911 17:15 Tagna
921 17:12 Esentuki
I have struct train. And I had placed some of theese “trains” in the heap using double pointer. I decided to debug my project, by using memory dump window. I wanted to find my structures in heap, but I found some obscure behavior of this codeblock function. When I typed in search bar expresion “ptrs.destination”, somehow it gets field of object “*ptrs[0]”, or as it is an expression “ptrs[0]->destination”. I think that ptrs haven’t any fields, it is just a pointer.
This is in my opinion more correct query
why there is no error?
I’ ve also tried some other expression “ptrs->destination”, “(&ptrs)->destination”, that seem to be invalid, with all the same result.
Ferromantum is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4
You are correct that ptrs.destination
is not a valid C expression. Using it in your program would result in a compilation error.
If the Address box is supposed to accept a C expression, that would be a bug. If. I don’t know if that’s the case or not.