prg_list_elem_find()
Abstract
Finds an element in a source list and returns a pointer to it.
Syntax
prg_list_elem_find (list_ptr, test_func, elem_ptr, low_bound_pos_ptr, high_bound_pos_ptr)
| Argument | Type | Description |
|---|---|---|
list_ptr |
PrgT_List * |
pointer to the list-of-interest |
test_func |
PrgT_List_Compare_Proc |
procedure called to determine whether an element matches search criteria |
elem_ptr |
void * |
element against which other elements in the list are compared. |
low_bound_pos_ptr |
int * |
area to be filled with a pointer to a list element. See Details. |
high_bound_pos_ptr |
int * |
area to be filled with a pointer to a list element. See Details. |
Return Type
Vartype *
Pointer to the found element, or PRGC_NIL if no element was found.
Header
prg_list_funcs.h
Example:
/* use the 'find' to find in the sorted list */
j = (int) prg_list_elem_find (my_list, prg_test_int_compare,
(const void *) ((num_elems / 2) * (num_elems / 2)),
PRGC_NIL, PRGC_NIL);
if (j != ((num_elems / 2) * (num_elems / 2))) {
aprintf (FLINE, "did not find element (%d) as expected, found %d instead",
(num_elems / 2) * (num_elems / 2), j);
}
....
int
prg_test_int_compare (const void *value1, const void *value2)
{
int i, j;
i = (int) value1;
j = (int) value2;
if (i < j) { FRET (1); }
else if (i > j) { FRET (-1); }
else { FRET (0); }
}
Details
The source list specified by list_ptr must already be sorted (using test_func) before this function is called. There are two ways to sort the list in this manner:
- call
prg_list_sort()with the same comparison procedure - add all items to the list with
prg_list_insert_sorted()
The test_func procedure is applied to a list element and elem_ptr to determine if a match is found. The following table shows the values returned and filled into low_bound_pos_ptr and high_bound_pos_ptr for different conditions.
| Return Value | low_bound_pos_ptr | high_bound_pos_ptr | ||
|---|---|---|---|---|
| Match is found and… | …list is sorted | address of matching element with lowest index | position of matching element with lowest index | position of matching element with highest index |
| …list is unsorted | same as low_bound_pos_ptr |
|||
| No match is found and… | …list is sorted | OPC_NIL |
position of element next-lowest to high_bound_pos_ptr,or –1 if none |
position at which to insert elem_ptr to maintain a sorted list |
| …list is unsorted | –1 | –1 |
The test function prototype is given in PrgT_List_Compare_Proc.
WARNING: This function is MT unsafe, as described in “Multi-Threading Safety“ on page 11. Access to shared lists must be externally serialized.
Purpose:
To search for and return a specific element in a PrgT_List, if the element’s position in the list is not known.
Errors:
- Program Abort: Segmentation violation. (due to an invalid list pointer or malformed list)
Reference:
- use
prg_list_insert()to insert an element into a list - use
prg_list_insert_sorted()to insert an element into a sorted list