How can i make a 2d array arr[][]
using two 1d arrays arr1[] arr2[]
of different sized,
like arr1 = {1,2,3}
arr2 = {4,5}
and it should looks like:
arr[][] = 1 2 3
4 5
How can i make a 2d array arr[][]
using two 1d arrays arr1[] arr2[]
of different sized,
like arr1 = {1,2,3}
arr2 = {4,5}
and it should looks like:
arr[][] = 1 2 3
4 5
You can't do that on C++, the only two ways are pointers or the stl vector, which I would recommend for being easier.
Something like this (using C++11):
#include <vector>
using namespace std;
int main(){
vector< vector<int> >arr = {{1, 2, 3}, {4, 5}};
}
If you can't use C++11, you can still initialise the vector adding every value inside a loop or one by one using push_back()
.
You can't have a multidimensional array by using arr[][]
because you must declare the size of the array in advance. For instance the following is valid, but the array is only partly initialised:
#include <iostream>
int main() {
int arr[][4] = {
{ 1, 2, 3 },
{ 4, 5 },
{ 6, 7, 8, 9},
};
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 4; ++j)
{
std::cout << arr[i][j] << std::endl;
}
}
}
Your other alternative is to dynamically declare the array:
int* arr[3] {
new int[4] { 1, 2, 3 },
new int[2] { 4, 5 },
new int[4] { 6, 7, 8, 9},
};
You would or course, need a record of array lengths and need to free the memory afterwards!
And this is all assuming you can't use std:vector
, which would be ideal.