-1

Im learning at the moment c++ with a book. I have many problems with the pointers...

int i;
cin >> i;
const int *quantity = &i;

int array[*quantity];

Is that correct? Can i control now the size of the array during the programm is running?

Skeptar
  • 179
  • 3
  • 12

3 Answers3

1

That's very nearly correct, except that the size of the array (which you've attempted to allocate on the stack here) has to be known at compile time, so no you can't do this.

However, you can allocate an array at runtime using new[], which will let you pass in a size that's not a compile time constant (new allocates on the heap):

int* array = new int[*quantity];
// ...
delete[] array;    // Manual allocations with `new` require manual deallocations

Note that in your particular code example, there's no need to play with pointers at all -- you can just use i directly:

int* array = new int[i];
Cameron
  • 96,106
  • 25
  • 196
  • 225
0

No, this is incorrect. Array size must be a constant expression, which means that it can be evaluated during compilation, and this is not the case for your code.

If you want arrays of different sizes, you can use dynamic allocation:

int* array = new int[i];

Or much better use std::vector:

std::vector<int> array(i);
Anton Savin
  • 40,838
  • 8
  • 54
  • 90
0

Arrays are a fixed size in memory. Because arrays also represent a contiguous block of objects in memory, by definition the same array cannot change size in memory, because it would then need to move memory that may not even belong to the same application.

There are ways to move your array, however, copying it to a new array with more space when it gets full, and there are more mutable types such as std::Vector, but an array as deifned here cannot ever change size.

What this code would instead do is

  • place a value in i
  • Place a value in quantity representing the address (pointer) of i
  • Create a new array using the value in the address quantity

Note that pointers are addresses, specifically saying the byte address in RAM of a given variable (try printing a pointer directly, for example!). The * and & operators quickly say "get value at address" and "get address of"

David
  • 10,458
  • 1
  • 28
  • 40