What is the point of pointers?

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

    It sounds to me like you haven't yet learned about dynamic memory allocation. There are two ways to allocate memory in C++: statically and dynamically. You are already familiar with static allocation (i.e. - declaring variables). This is great if you know at the time of writing your program exactly how many variables (or rather, memory) you need.

    But what if you don't? For example, let's say you're reading that contains a bunch of numbers you need to keep track of. Why? I don't know but that's not the point.

    Well you could start with an array:

    int array[100];
    

    But what if there are more than 100 numbers in the file? Eventually you'll want a more flexible solution:

    int *array = new int[size];
    // do stuff
    delete [] array;
    

    This gives you a lot more flexibility and lets you create more dynamic data structures.

提交回复
热议问题