C++ new array
In C++, you can create a new array using the new
keyword. Here's an example:
int* myArray = new int[5];
This creates a new array of 5 int
elements, and assigns it to the pointer myArray
.
Note that new
returns a pointer to the first element of the array, so you can access the elements using the pointer arithmetic:
myArray[0] = 1; // sets the first element to 1
myArray[1] = 2; // sets the second element to 2
And so on.
When you're done using the array, you need to delete it using the delete
keyword to free up the memory:
delete[] myArray;
The []
is important, as it tells delete
that it's deleting an array, rather than a single object.
Alternatively, you can use the std::vector
class, which provides a more convenient and safer way to work with arrays:
std::vector<int> myVector(5);
myVector[0] = 1; // sets the first element to 1
myVector[1] = 2; // sets the second element to 2
With std::vector
, you don't need to worry about deleting the memory, as it takes care of it automatically when the vector goes out of scope.
Here's a complete example:
#include <iostream>
#include <vector>
int main() {
// Create a new array using new
int* myArray = new int[5];
myArray[0] = 1;
myArray[1] = 2;
std::cout << "Array elements: ";
for (int i = 0; i < 5; i++) {
std::cout << myArray[i] << " ";
}
std::cout << std::endl;
// Delete the array using delete
delete[] myArray;
// Create a vector
std::vector<int> myVector(5);
myVector[0] = 1;
myVector[1] = 2;
std::cout << "Vector elements: ";
for (int i = 0; i < 5; i++) {
std::cout << myVector[i] << " ";
}
std::cout << std::endl;
return 0;
}
This example demonstrates both the new
and delete
keywords, as well as the std::vector
class.