In C++, delete
is used to deallocate memory that was allocated using the new
operator for a single object, while delete[]
is used to deallocate memory that was allocated using the new
operator for an array of objects.
Here's an example of using delete
to deallocate memory for a single object:
int* ptr = new int; // allocate memory for a single int
*ptr = 5; // set the value of the int
delete ptr; // deallocate the memory
In this example, we allocate memory for a single integer using the new
operator and assign a value to it. Then, we deallocate the memory using the delete
operator.
And here's an example of using delete[]
to deallocate memory for an array of objects:
int* arr = new int[5]; // allocate memory for an array of 5 ints
for(int i = 0; i < 5; i++) {
arr[i] = i; // set the value of each element in the array
}
delete[] arr; // deallocate the memory
In this example, we allocate memory for an array of 5 integers using the new
operator and assign values to each element of the array. Then, we deallocate the memory using the delete[]
operator.
Using delete
instead of delete[]
or vice versa can lead to undefined behavior, which can cause crashes or other unexpected errors in your program. Therefore, it's important to use the correct operator depending on how the memory was allocated.
Comments
Post a Comment