-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?

2
  • 1
    1. There is no point of using pointer here. You could use int array[i] (in C). 2. C++ does not support VLA (Variable Length Array) Commented Nov 5, 2014 at 22:28
  • Avoid arrays; prefer std::vector. (In general, and especially as a beginner.) Commented Nov 5, 2014 at 22:33

3 Answers 3

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]; 
Sign up to request clarification or add additional context in comments.

Comments

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); 

Comments

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.