0

I need a help with c++.

int *tab1[5];
int tab2[] = {3, 4, 5};
tab1[0] = tab2;

It works but I want to have a variable instead of 5 in first line. Any ideas? Thanks you in advance.

empthy
  • 19
  • 4
  • 20
    [`std::vector`](http://en.cppreference.com/w/cpp/container/vector). Always `std::vector`. – Some programmer dude Mar 08 '18 at 11:59
  • 1
    arrays should ALWAYS be compile time constants (even if your compiler has an extension to allow you to use variables). You can get away with `constexpr unsigned int arraySize=5` but that's not a variable in the way I think you want it to be. – UKMonkey Mar 08 '18 at 12:00
  • Possible duplicate of [How to create a dynamic array of integers](https://stackoverflow.com/questions/4029870/how-to-create-a-dynamic-array-of-integers) – alseether Mar 08 '18 at 12:04

2 Answers2

1

Since you found the "wrong" answer I'll show you the "correct":

#include <iostream>
#include <vector>

int main()
{
    std::cout << "How many lines do you want? ";
    unsigned lines;
    if (!(std::cin >> lines))
    {
        std::cout << "Invalid input\n";
        return 1;
    }

    std::vector<std::vector<int>> tab(lines);

    if (lines > 0)
    {
        tab[0] = { 3, 4, 5 };
    }
}
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550
0

I found an answer,

int n = 5;
int **tab1 = new int*[n];
int tab2[] = {3, 4, 5};
tab1[0] = tab2;

Thanks for your attention.

empthy
  • 19
  • 4