In many tutorials, the first code samples about dynamic memory start along the lines of:
int * pointer;
pointer = new int; // version 1
//OR
pointer = new int [20]; // version 2
They always proceed to explain how the second version works, but totally avoid talking about the first version.
What I want to know is, what does pointer = new int
create? What can I do with it? What does it mean? Every tutorial without fail will avoid talking about the first version entirely. All I've found out (through messing about) is this:
#include <iostream>
using namespace std;
int main()
{
int * pointer;
pointer = new int;
pointer[2] = 1932; // pointer [2] exists? and i can assign to it?!
cout << pointer[2] << endl; // ... and access it successfully?!
};
The fact that I can subscript pointer
tells me so far that pointer = new int
implicitly creates an array. But if so, then what size is it?
If someone could help clear this all up for me, I'd be grateful...
This is a typical error in C and C++ for beginners. The first sentence, creates a space for holding just an int
. The second one creates a space for holding 20 of those int
s. In both cases, however, it assigns the address of the beginning of the dynamically-reserved area to the pointer
variable.
To add to the confusion, you can access pointers with indices (as you put pointer[2]
) even when the memory they're pointing is not valid. In the case of:
int* pointer = new int;
you can access pointer[2]
, but you'd have an undefined behavior. Note that you have to check that these accesses don't actually occur, and the compiler can do usually little in preventing this type of errors.