Reputation: 507
I have a piece of code that deals with C++ array.
using namespace std;
#include <iostream>
int main(){
int *p;
p = new int[3];
for(int i = 0; i < 3; i++){
p[i] = i;
}
//delete[] p;
for(int i = 0;i <3; i++){
std::cout << *(p+i) << std::endl;
}
}
How does this code work? How does the memory location *(p+i) work? How is it different from using p[i]. What are the differences on the code if we uncomment the line delete[] p.
Upvotes: 2
Views: 1022
Reputation: 3427
1) When you do this:
p = new int[3];
Now, p
points to the first element of the dynamically allocated array.
When you do, *(p + i)
will lead to simple pointer arithmetic. It will boil down to: value of (<address pointed by p> + <size of type pointed by p> * i
) which is equivalent to doing p[i]
.
That's why it works.
2) In C++, unlike java, you have to explicitly clear the dynamically allocated memory using delete
, as there is no GC in C++ (and will never be, as per Bjarne Stroustrup). Otherwise, the memory area will remain acquired for the application lifetime, thereby causing memory leak.
Suggestion:
Place your delete
at the end of the program. Otherwise, the loop below it may give SIGSEGV.
Also, Avoid using new
and delete
as much as you can.
Upvotes: 4