I have the following array structure (linked list):
struct str_pair
{
char ip [50] ;
char uri [50] ;
str_pair *next ;
} ;
str_pair *item;
I know to create a new item, I need to use
item = new str_pair;
However, I need to be able to loop through the array and delete a particular item. I have the looping part sorted. But how do I delete an item from an array of structures?
What you’ve shown is not an array of
struct, but a linked list ofstructcontaining arrays (of typechar).An array of
structwould look like this:If you actually have something like this, you don’t need to
deletesingle items from an array. Let’s say you’ve initialized your array as follows:Then you delete the whole array (including all of its items) using:
Again, you can’t
deletesingle items in an array allocated withnew[]; you perform adelete[]on the whole array.If, on the other hand, you intended to say “linked list of
struct“, then you’d generally delete an item similarly to the following:Or, in English: Find the item (A) preceding the item which you want to delete (B), then adjust A‘s “next” pointer so that B will be skipped in the list, then delete B.
You need to be careful with special cases, i.e. when the item to be removed from the list is the first item or the last one. The above code is not sufficient when you want to delete the first item in the list, because there will be no
previous_item. In this case, you’d need to change the pointer to the list’s first element to the second element.Your code:
Some things are wrong here:
If
headis null, the testcurr->next != NULLwill cause a segfault. (You must never dereference a null pointer!)Your code for removing an item from the list is completely incorrect. Worst of all, you delete a node without changing the previous item’s next pointer. The previous item will thus reference an item that’s no longer there.
A detail:
curr = head;before thereturnstatement doesn’t do anything useful at all.Suggested code:
Do it in two steps: One function to find the node to be deleted via its attached
uri, and one function to remove the node. You could separate it even better than the code below does, but it should be a starting point: