Entry
How do I define and Use Dynamic Array in C++?
Oct 30th, 2003 02:18
Colin Thomsen, Rafael Udaondo, Lam Ho,
See this sample with a int array:
int *array = new int[ 256];
array[ 0] = 10;
array[ 1] = 2;
printf( "%d %d", array[ 0], array[ 1]);
Note by Colin Thomsen.
These days you should be able to get by without using arrays at all
(unless you have to interface to legacy C code).
The key is to pick a container from the Standard Template Library (STL)
such as a vector. STL containers:
- are highly optimised
- handle memory allocation automatically (dynamic resize)
- allow you to make the equivalent of an array for objects without
default constructors
- provide bounds checking if you use the 'at' method
- provide a size method
For example
#include <vector>
#include <iostream>
int main()
{
// allocate 256 elements for a variable called container
std::vector<int> container(256);
container[0] = 10;
container[1] = 2;
// Use streams instead of printf, since they are typesafe
std::cout << container[0] << " " << container[1] << std::endl;
// use another container without knowing final size
std::vector<int> container2;
container2.push_back(10);
container2.push_back(2);
std::cout << container2[0] << " " << container2[1] << std::endl;
std::cout << "Size : " << container2.size() << std::endl;
}