-3

I am new to programming and I cannot figure out how to delete and array.

int* array = new int[5];

I tried to delete the array like this

delete array[5];

but I get an error: cannot delete expression of type 'int'

I also tried

delete [5]array;

but I got an error: error: expected expression

How do I delete an array? I don't know what else to do?

Thanks in advance for any help. It is very appreciated.

  • 7
    It looks like you are trying to learn C++ and its syntax based on guessing. That does not work. You should take a step back and systematically learn the language from a good book. – Baum mit Augen Apr 27 '18 at 07:24
  • Just about *any* book should have told you how to do it. If you don't have one, then consider [this list of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Apr 27 '18 at 07:24
  • 3
    Also, dynamic allocation using `new` and `delete` is good to know and learn, but once you do know how to use them, they're often not needed. In your example, if you want a "dynamic array" of `int` elements, use [`std::vector`](http://en.cppreference.com/w/cpp/container/vector), as in `std::vector array(5);` which defines `array` to be a vector of five elements. – Some programmer dude Apr 27 '18 at 07:26
  • ` delete[] array;` –  Apr 27 '18 at 07:28
  • Sorry I tried searching in search bar but did not see anything. Should I delete this? – user9708849 Apr 27 '18 at 07:29
  • Thank you programmer dude. I do not have a book though – user9708849 Apr 27 '18 at 07:30

3 Answers3

1

try delete []array; that would do. array is one pointer pointing to the beginning of the 5-element dynamic-array so you only have to delete one pointer.

Narek Bojikian
  • 259
  • 3
  • 13
  • 1
    It’s not a dynamic pointer. It’s a pointer to dynamically allocated memory. A dynamic pointer would be a pointer created on the heap. – Blair Fonville Apr 27 '18 at 07:34
  • 1
    You don't delete pointers, you delete the things they point to. It's an important distinction, in particular to a beginner. – molbdnilo Apr 27 '18 at 07:40
1

Use the following:

delete [] array;   // Delete an array
array = 0;      // Clear array to prevent using invalid memory reference
Gaterde
  • 779
  • 1
  • 7
  • 25
0

The correct usage is delete []array. You do not need to specify the size when calling delete.

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73