2

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.

3
  • p+i is p offset by i objects. *(p+i) is not different from p[i]. If you uncomment delete[] p you'll later access a released memory which is an UB. Commented Jan 22, 2019 at 0:23
  • @ihavenoidea - Of course I tried, but I need to know how it works. . Commented Jan 22, 2019 at 0:23
  • Where did you get the code from? Commented Jan 22, 2019 at 0:24

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.