Why do we need pointers to arrays when we have regular arrays?

Viewed 87

What's the need of pointers array when we already have simple arrays for array data? We can already use arrays to store data; why would we ever want to use pointers to arrays?

int array[100];
int *ptr = new int[100]
2 Answers

There are several reasons to use dynamically-allocated arrays rather than arrays that are local variables.

  1. Space limitations. If you declare an array as a local variable, it’s typically stored in a region of memory called the stack. The stack has limited size and space, usually on the order of tens of megabytes, and if you exceed this space your program will crash. If you want to process large data sets (say, hundreds of megabytes), then you’ll need to use dynamic allocation. (To see this, try creating an array of 100,000,000 integers as a local variable and setting them all equal to their index.)
  2. Space efficiency. Dynamic allocation allows you to size your arrays at runtime, when you know how much space you’ll need. Local variable arrays, however, have to have a fixed size. If that size is too small, you can’t store all the data you need. If it’s too big, it’s an inefficient use of memory.
  3. Array lifetimes. A local variable ceases to exist as soon as the block it’s declared in exits. If you use local arrays, the array contents cease to exist as soon as the function they’re declared in finishes running. Dynamically allocated objects exist until they’re explicitly cleaned up.

Space limitations. Which is the main reason for the detailed pointers in an array. So that the variables and the values that we include in the array only will be attached to that specific index so that the space complexity will not occur

Related