The goal was to create a structure, write numbers from a file into it in descending order, and add a couple of numbers from the keyboard and output to the standard output stream .

On one of the forums I found a rather capacious and compact way, but I don’t quite understand what is going on there (we are talking about the Push function).

If someone can explain what is happening in it, the role of variables in this function would be very grateful.

I know, of course, that sorting out someone else's code is not the most pleasant thing, so forgive me (

Link to the original: http://www.cyberforum.ru/c-linux/thread1009675.html

#include <stdio.h> #include <stdlib.h> typedef struct _TNode { double value; struct _TNode* next; } TNode; //----------------------------------------------------------------------------- TNode* Push(TNode** list, double value) { TNode** tmp = list; TNode* node = malloc(sizeof(TNode)); node->value = value; while ( *tmp && ((*tmp)->value > value) ) { tmp = &(*tmp)->next ; } if (*tmp) { node->next = *tmp; } *tmp = node; return *list; } //----------------------------------------------------------------------------- void Print(const TNode* list) { while (list) { printf("%.1lf ", list->value); list = list->next; } printf("\n"); } //----------------------------------------------------------------------------- int main(int argc, char* argv[]) { FILE* f = stdin; TNode* list = NULL; double value; if (argc > 1) { if ((f = fopen(argv[1], "r")) == NULL) { perror(argv[1]); return 9999; } } while ((fscanf(f, "%lf", &value)) == 1) { Push(&list, value); } while ((scanf("%lf", &value)) == 1) { Push(&list, value); } Print(list); return 1111; } 
  • one
    Push() adds a new element to the ordered list of numbers in descending order. By the way, there is an error there (apparently it did not manifest itself when tested by the author, since he always received fresh memory), after malloc, the next field of the received structure should be reset. - avp pm
  • With the variables in it, try yourself to deal with the pencil and paper, invent the addresses that malloc gives (and go ahead -)) - avp
  • On one of the forums I found a rather capacious and compact way, but I don’t quite understand what is happening there - implement it all by yourself, otherwise you won’t understand - VTT

0