Create a two-dimensional array at runtime: Difference between revisions
Content added Content deleted
(new task; C++) |
m (→[[C++]]: Fixed language link, added category) |
||
Line 2: | Line 2: | ||
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then oputput that element. Finally destroy the array if not done by the language itself. |
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then oputput that element. Finally destroy the array if not done by the language itself. |
||
==[[C++]]== |
==[[C plus plus|C++]]== |
||
[[Category:C plus plus]] |
|||
With language built-in facilities: |
With language built-in facilities: |
||
Revision as of 00:45, 27 February 2007
Create a two-dimensional array at runtime
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then oputput that element. Finally destroy the array if not done by the language itself.
C++
With language built-in facilities:
#include <iostream> #include <istream> #include <ostream> int main() { // read values int dim1, dim2; std::cin >> dim1 >> dim2; // create array double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i; // write element array[0][0] = 3.5; // output element std::cout << array[0][0] << std::endl; // get rid of array delete[] array; delete[] array_data; }
Using std::vector from the standard library:
#include <iostream> #include <istream> #include <ostream> #include <vector> int main() { // read values int dim1, dim2; std::cin >> dim1 >> dim2; // create array std::vector<std::vector<double> > array(dim1, std::vector<double>(dim2)); // write element array[0][0] = 3.5; // output element std::cout << array[0][0] << std::endl; // the array is automatically freed at the end of main() }