Bifalgorithm post · Computer science one · Searching

How does lsearch() search an array and insert a missing element?

How does lsearch() search an array and insert a missing element? (Computer science one · Searching) — "In the same library, there is another linear search func…

Ideas in this flowchart

  • lsearch() réalise une recherche linéaire et peut insérer un élément absent.
  • Signature : void *lsearch(const void *key, void *base, size_t *nmemb, size_t size, int(*compar)(const void *, const void *));
  • En l’absence d’un élément correspondant, la fonction retourne NULL et tente une insertion.
  • La fonction retourne NULL si aucun élément correspondant n’est trouvé.
  • L’élément recherché est inséré à la fin du tableau.
  • L’insertion suppose qu’il reste suffisamment d’espace valide à la fin du tableau.
  • Si l’espace disponible est insuffisant, le comportement est indéfini.
  • Le fait que base ne soit pas const indique que la fonction peut modifier le tableau.
  • nmemb est transmis par référence afin de pouvoir être modifié.
  • Après une insertion, la variable nmemb est incrémentée pour représenter le nouvel élément.
  • Il faut garantir soi-même une mémoire valide suffisante pour les insertions.
Feed/

How does lsearch() search an array and insert a missing element?

No cover

Channel

Computer science one

1 page

"In the same library, there is another linear search function:\n\nvoid *lsearch(const void *key, void *base, size_t *nmemb, size_t size, int(*compar)(const void *, const void *));\n\nIt differs in that if it does not find a matching element, it still returns NULL but also attempts to insert the element being searched for at the end of the array. The function will assume there is enough room at the end of the array to accommodate the inserted element (if not, the behavior is undefined). This behavior is hinted at by the fact that base is not const. Moreover, nmemb is passed by reference. If the function inserts the element, it will also increment nmemb variable to reflect this new element. It is your responsibility to ensure that there is enough valid memory to accommodate any inserts when using lsearch()."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.