pointer as second argument instead of returning pointer?

后端 未结 7 422
长情又很酷
长情又很酷 2021-01-18 05:33

I noticed that it is a common idiom in C to accept an un-malloced pointer as a second argument instead of returning a pointer. Example:

/*functi         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 05:52

    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.

提交回复
热议问题