0
new and delete operator
Hi,I still couldn't understand why are we using new and delete. Can someone please explain me clearly, thanks.
3 Respostas
+ 1
Lets say you have code like this:
int *p = new int;
Pointer p now stores address to 4 bytes (is size of int 4 bytes?) of allocated memory. You can store something into this allocated memory like this:
*p = 665;
std::cout>>*p;
Now if you want to free this allocated memory, you can use delete like this:
delete p;
If you dont free this memory, and pointer gets out of scope, you will have no access to this memory.
Example:
void func() {
int *p = new int;
}
*p = 7; //error
//Pointer got deleted, but allocated memory did not. You cant access this memory now, because you dont have pointer to it.
Not 100% sure if its right, but thats how I understand it.
0
actually I still couldnt understand, i think i have problem with my brain 😃, thanks for answer.
0
I will try to explain it to you better.
Pointer stores address (location somewhere in memory) and with "new" we basically reserve n bytes of memory and assign address of 1st byte in our memory, which we reserved to our pointer.
Same example as before:
int *p = new int;
int *p is pointer. (Stores location in memory)
new int will reserve size of int and return address of first byte