First create a structure

struct LIST { int field; struct LIST *pNext; }; struct LIST* pHead; инициализирую первый элемент struct LIST* init(int number) { struct LIST *lst; lst = (struct LIST*)malloc(sizeof(struct LIST)); lst->field = number; lst->pNext = NULL; return lst; }; struct LIST* add(struct LIST* lst, int number) { struct LIST * pNew; pNew = (struct LIST*)malloc(sizeof(struct LIST)); pNew->field = number; pNew->pNext = lst->pNext; //2 lst->pNext = pNew; //3 return pNew; } int main() { pHead = init(5); struct LIST* pTmp = add(pHead, 10); } 

Question: how does the add function work, it is especially incomprehensible what is being done here, what happens with pointers and how to understand this lst-> pNext Why does the call have to happen via pNew and how does it differ from the call with lst?

 pNew->pNext = lst->pNext; //2 lst->pNext = pNew; //3 

And can you please explain what the program does in general?

    1 answer 1

    This is not an add, but an insert after the lst element. The function should be called insert .

    The lst object has a pointer to the list item that follows it. The function inserts a new pNew element after lst . therefore

     lst->pNext = pNew; 

    but the element that used to follow lst will now go after pNew . therefore

     pNew->pNext = lst->pNext; 

    These two actions are performed in the reverse order in order not to overwrite the initial value lst->pNext .

    treatment ... via pNew and how it differs from treatment using lst

    These are pointers to two different objects. It's not entirely clear what you want to ask.

    • and what lst-> pNext generally does, how does this composite type pointer interact with pNext? Does each pNew or lst have its own pNext? - Elvin
    • @Elvin Yes, everyone has his own. Can you imagine the meaning of the words "simply linked list"? - Igor
    • c work, but apparently it’s a chain, “carriages” of the same type, interconnected by pointers, and it seems to be all recursive - Elvin
    • @Elvin Yes, each carriage has a pointer to the next one. The value of this pointer is NULL last carriage. - Igor