What is the point of pointers?

后端 未结 12 1316
梦谈多话
梦谈多话 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:34

    At the most basic level, pointers allow you to associate disjoint blocks of memory. A simple (contrived, admittedly) example of where pointers could help you would be in an algorithm that requires an array of 1000000000000 integers. Such an array would be too large to fit within the RAM of the machine on which I am typing right now if I tried a definition such as:

    int bigMatrix[1000000000000]; // I can't allocate this much contiguous memory
    

    However, if I create a single array of pointers, I can keep the sub-arrays on a middle-sized disk array.

    int *bigMatrix[1000000]; // Each pointer refers to a sub-array 
                             // of 1000000 elements on disk
    

    Admittedly, I will have to write code to page in those sub-arrays if / when the user requires them, including hiding the array notation behind an accessor method. That said, pointers allow me to create the ad-hoc associations that I need when I need them.

提交回复
热议问题