I noticed that it is a common idiom in C to accept an un-malloc
ed pointer as a second argument instead of returning a pointer. Example:
/*functi
An issue not discussed in this article is the matter of how you go about referring to the malloc'ed buffer within the function that allocates it, and presumably, stores something in it before it returns control to its caller.
In the case that brought me to this page, I have a function that passes in a pointer, which receives the address of an array of HOTKEY_STATE structures. The prototype declares the argument as follows.
HOTKEY_STATE ** plplpHotKeyStates
The return value, ruintNKeys, is the number of elements in the array, which is determined by the routine before the buffer is allocated. Rather than use malloc() directly, however, I used calloc, as follows.
*plplpHotKeyStates = ( HOTKEY_STATE * ) calloc ( ruintNKeys ,
sizeof ( HOTKEY_STATE ) ) ;
After I verify that plplpHotKeyStates is no longer null, I defined a local pointer variable, hkHotKeyStates, as follows.
HOTKEY_STATE * hkHotKeyStates = *plplpHotKeyStates ;
Using this variable, with an unsigned integer for a subscript, the code populates the structures, using the simple member operator (.), as shown below.
hkHotKeyStates [ uintCurrKey ].ScanCode = SCANCODE_KEY_ALT ;
When the array is fully populated, it returns ruintNKeys, and the caller has everything it needs to process the array, either in the conventional way, using the reference operator (->), or by employing the same technique that I used in the function to gain direct access to the array.