When you use
new, you are
not using it to allocate memory for the pointer that will point at that memory.
I'll repeat that.
When you use
new, you are
not using it to allocate memory for the pointer that will point at that memory.
Look at this code:
int* p = new int;
The
new allocates memory for an
int. For an
int. It does
not, repeat does
not, allocate memory for the pointer
p. The pointer is a complete object that exists on the stack; the memory it takes up does not, does NOT, get allocated by
new. After this code, we now have TWO objects. A pointer called
p, and an
int that has no name that we get access to using the pointer
p.
So, back to your question:
Let's suppose we have two non pointer variables.. int x; char y; how can we allocate and deallocate memory for these two non pointer variables? |
Like this:
1 2
|
char* pointerOne = new char;
int * pointerTwo = new int;
|
The
new here has allocated memory for an
int, and memory for a
char. The pointers are not, repeat
not, allocated memory by
new. The pointers are just
how you get access to the memory
new has allocated.
When you decide you want to deallocate them, you can use
delete:
1 2
|
delete pointerOne;
delete pointerTwo;
|
However, you should only use
new when you have to. Otherwise, just put them on the stack like this:
1 2
|
char variableOne;
int variableTwo;
|