What is the point of pointers?

后端 未结 12 1333
梦谈多话
梦谈多话 2021-02-01 18:49

What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them?

12条回答
  •  逝去的感伤
    2021-02-01 19:25

    Suppose you write a text editor. In this case, you don't know the size of the document in advance. You might be tempted to declare something like

      char Document[10000];
    

    but then certainly some day someone you will want to use your editor on a much larger document. So this attempt is futile; and what you need is a way to ask for new memory at runtime (instead of compile time).

    The C++ way of doing this is using the operator new, which returns a pointer to the freshly allocated memory:

      char* pDocument = new char[getSizeOfDocument()];
    

    (Note that this example is oversimplified. In real life, you would certainly not do it like this but instead use something like std::string and std::vector, which internally do this allocation for you.)

提交回复
热议问题