When to use Pointer-to-Pointer in C++?

后端 未结 6 1636
小鲜肉
小鲜肉 2021-02-13 20:38

I was wondering when we use Pointer to Pointer in C++ and why we need to point to a pointer? I know that when we point to a pointer it means we are saving the memory address of

6条回答
  •  星月不相逢
    2021-02-13 21:07

    You have probably seen int main() before, have you seen this:

    int main(int argc, char** argv)
    

    argv is indeed a double pointer, it's not actually a double pointer but it is a pointer to an array of pointers, each pointing to an array of characters pertaining to the command line arguments.

    This is not the best example, as you probably want a more practical example. I will write up a better example and edit my post :)

    Edit:

    If you are familiar with classes and virtual functions then you may also be aware that any class who has a virtual function is automatically given a _vftp member variable.

    The _vftp member is a pointer to a list of all the function pointers to your virtual functions. It is inserted at the very beginning of the structure. If you created a new object as follows:

    class myclass
    {
    public:
        //void *_vftp; this is where the _vftp member gets inserted automatically
        virtual void vfunc1();
    };
    
    void myclass::vfunc1() {printf("yay");}
    
    void main() {
        myclass *pMyObject = new myclass();
    }
    

    Upon instantiating myclass, the _vftp is added to the object structure and it is the very first variable. Because pMyObject is a pointer to this structure in memory, *pMyObject is eqal to _vftp.

    Because _vftp is a pointer to the array of virtual function pointers, *_vftp is equal to vfunc1 (a function pointer).

    This means if we dereference pMyObject twice, and call it, we will call vfunc1():

    typedef (void* (__thiscall* fnVFunc1))(void);
    ((fnVFunc)**pMyObject)();
    

    Although this is not a real use for double pointers this is a prime example of applying them. The most common place for double pointers lays in hacking and reverse engineering, where you commonly need to find a pointer in memory and alter whatever it points to.

提交回复
热议问题