-2

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  
imnain
  • 69
  • 5
  • 3
    c or c++? why do you use the `pointer` tag? Seems like you have already a solution in mind. If yes, please show your code. If not, forget about pointers and use `std::vector` – 463035818_is_not_an_ai May 08 '18 at 09:58
  • You can't have 2D array with varied 1D array sizes. – machine_1 May 08 '18 at 09:59
  • @machine_1 is that c/c++ specific? because im pretty sure you can in other languages – mast3rd3mon May 08 '18 at 10:01
  • @mast3rd3mon yes, c++ needs array lengths, apart from the first dimension, which is inferred. Other languages "arrays" are actually more like c++'s "vectors". – c z May 08 '18 at 10:13
  • seems a bit odd for people to downvote without comment considering this can be done in other languages though. – c z May 08 '18 at 12:08

2 Answers2

0

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().

jesusjimsa
  • 325
  • 1
  • 3
  • 13
-1

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.

c z
  • 7,726
  • 3
  • 46
  • 59
  • "_but the array is only partly initialised_" There's no such thing as "partial initialization". It is _fully_ initialized. As in, the array elements that you didn't give the value explicitly, are default-initialized (which is `0` for numeric types). – Algirdas Preidžius May 08 '18 at 10:52
  • @AlgirdasPreidžius true that. For clarity "Partial Initialization is a non-standard terminology which commonly refers a situation where you provide some initializers but not all " - https://stackoverflow.com/questions/10828294/c-and-c-partial-initialization-of-automatic-structure – c z May 08 '18 at 12:15