cbstmap · Section 3
cbmap_get_ptr
NAME
cbmap_get_ptr - get pointer to value by key (type-inferred)
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/cbstmap.h> value_ptr = cbmap_get_ptr(hm_name, key);
DESCRIPTION
Type-inferred wrapper for cbstmap_get_elem_ref() that returns a pointer to the value, or NULL when the key is not in the map. cbmap_get() stops the program in that case and this macro doesn't. The lookup key is converted through the DECLARED key type of the tree, just as cbmap_insert(3) converts it, so a key stored through that conversion is found again only by a lookup that makes the same conversion. Both a literal and a computed expression are accepted.
PARAMETERS
hm_name BST map to search key Key to look up
RETURN VALUE
A pointer to the value if the key is in the map. NULL if the key is not in the map. NULL if key is a NULL character pointer, which is not a string.
NOTES
The macro stops the program if the size of the value doesn't match the size of the type. Because it returns a pointer to the value, the caller can change the value in place. An insert or a delete makes the pointer invalid. For a char* value type the target of the pointer is const-qualified (char *const *). You can read the stored string and edit its bytes in place within the stored length, but replacing the pointer itself is a compile error. The map owns the string bytes and keeps its own accessor in step with them, and a replaced pointer would leave the accessor's length describing the older string. To replace a string value use cbmap_insert(3), which frees the old bytes and copies the new ones into storage that the map owns. The search takes O(log n) time.
EXAMPLES
cbmap_construct(map, int, int); int key = 42, val = 100; cbmap_insert(map, key, val); int* ptr = cbmap_get_ptr(map, key); if (ptr) { *ptr = 200; // Change the value in place } cbmap_construct(names, int, char *); cbmap_insert(names, key, "hello"); char *const *sptr = cbmap_get_ptr(names, key); if (sptr) { printf("%s\n", *sptr); // Read the stored string (*sptr)[0] = 'j'; // Edit its bytes in place: "jello" cbmap_insert(names, key, "a longer replacement"); // Replace the string } cbmap_destroy(map); cbmap_destroy(names);