In C++ is there any difference between the pointers p and q in the below code?
int* p = new int;
int* q = new int[5];
I understand that one allots new memory for a single int and the second allots memory for an array of 5 ints, but fundamentally is there any difference between a pointer pointing to a single int and one pointing to an array of ints?
I got this doubt because I read that one must use delete[] q
to free up memory pointed to by q but just delete p
for the single int pointed to by p.
What would happen if I used delete q
?
A user creates a pointer for storing the address of any given array. A user creates an array of pointers that basically acts as an array of multiple pointer variables. It is alternatively known as an array pointer. These are alternatively known as pointer arrays.
An array is a collection of elements of similar data type whereas the pointer is a variable that stores the address of another variable. An array size decides the number of variables it can store whereas; a pointer variable can store the address of only one variable in it.
Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.
The only difference between an array name and a normal pointer variable is that an array name always points to a specific address, which is the starting address of the array. Pointers are flexible and can point to wherever you want them to point.
The pointers themselves are completely indistinguishable. That's why you must remember to match new
/delete
and new[]
/delete[]
.
Mismatching them triggers undefined behaviour.
When using new []
some c++
implementations will track the size of the allocation of the array in the address before the pointer returned. This is an implementation detail not defined by the standard.
The following answer describes this possible implementation in a little more detail: How could pairing new[] with delete possibly lead to memory leak only?
You must always match new
with delete
and new []
with delete []
. It is Undefined Behavior to mix these.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With