A pointer is a variable which contains a number.
That number represents a memory address.
You can print the pointer to see what memory address it contains:
1 2 3 4 5 6 7
|
std::cout << ptr << '\n';
const char *s = "Hello, World!";
// a cast is required for char pointers, because they're
// treated differently than regular pointers
std::cout << reinterpret_cast<const void *> (s) << std::endl;
|
When the pointer is not initialized, it contains a garbage value.
The garbage value is not a valid memory address.
Possibly, if you compile in Debug mode (or without Optimizations) the pointer will be initialized to 0.
A pointer pointing to memory address 0 is called
NULL (or
nullptr in C++11).
And this is also an invalid memory address.
What does the
new operator do?
It allocates a chunk of memory then returns the address to it.
So your pointer will contain a valid memory address, and you can read/write to that chunk of memory.
Your first snippet is incorrect because you don't initialize the pointer, and a garbage value cannot be used safely, while a value of 0 cannot be used at all.
Your second snippet is correct.
Your third snippet is incorrect. You must use
operator new[] and
operator delete[] for dynamic arrays. Otherwise even if the code appears to work, it may crash randomly. In your snippet, you do not own the memory at which
ptr[4]
is located.
1 2 3 4 5
|
int *ptr = new int[5]; // available: ptr[0], ptr[1], ptr[2], ptr[3], ptr[4]
ptr[4] = 20;
std::cout << ptr[4] << std::endl;
delete[] ptr;
|
Edit: lots of mistakes and typos.