0

Hey so I want to create n arrays (based off user input) of size x (also off user input). The way I was thinking of doing it was having a for loop perform n iterations and inside the loop ask the user for x. The problem is I'm not sure how to name the array using the variable n, I was thinking something like:

cout << "Enter n: ";
cin >> n

for (i = 0; i < n; i++)
{
    cout << "Enter x: ";
    cin >> x;

    double*array+i;
    array+i = new double[x]
}

To sum up my question is: can you create/name an array using a variable in C++?

8
  • 2
    Can't do this in C++. You basically need to create an array of arrays (or, since this is c++, a vector of vectors) Commented Mar 2, 2013 at 18:57
  • 1
    "array named after for loop iterator" - Why would you need an array with specific name? This doesn't sound like a right thing to do. Just use std::vector< std::vector<double> >. Commented Mar 2, 2013 at 19:04
  • I'm not sure I understand what you're trying to do. If you are using C++, then go for a std::vector<std::vector<double>> myMatrix, which allows you to access items in the inner arrays like so: myMatrix[x][y]. If you want to use fixed-size arrays, then you can go for std::array<std::vector<double, N>, M> myMatrix, which creates an MxN matrix. Please use en.cppreference.com/w to understand how to work with these containers. Commented Mar 2, 2013 at 19:04
  • @MihaiTodor That is a terrible way to define a Matrix! Your memory will be all over the place; please do not advise people to do it like that! Commented Mar 2, 2013 at 19:06
  • Welcome to Stack Exchange Henry! It would be useful if you gave as much information as you can in your question. For example, why are you doing this? What are you trying to achieve? Commented Mar 2, 2013 at 19:07

3 Answers 3

1

Unfortunately, you can't do this in C++. Try something like this...

std::cout << "Enter n: ";
std::cin >> n

std::vector<std::vector<double> > arrays(n);

for (std::size_t i = 0; i < n; i++)
{
    std::cout << "Enter x: ";
    std::cin >> x;

    arrays[i].reserve(x);
}

reserve only allocates, but does not construct the objects in the std::vector; if you want to construct them too, use resize.

PS Never use using namespace std; it makes your code harder to read and debug.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, i'd change reserve to resize. reserve only changes capacity, not size
0

Since you are programming in C++, you should use STL containers (especially std::vector) instead of C-style arrays.

If you need to access an array by using the string that has been created in runtime, then you could use std::map< std::string, std::vector<double> >, which is pretty crazy idea though:

typedef std::vector<double> MyVector;
std::map<std::string, MyVector> myVectors;

// create an array:
std::string arrayName;
arrayName = std::string("someArray");       // could be: std::cin >> arrayName;
myVectors[arrayName] = MyVector(10, 1.23);  // new vector of size 10

std::cout << myVectors["someArray"][4];     // prints 1.23

I'm not sure what exactly is what you are trying to achieve, but there are most likely more appropriate solutions. Is it really necessary to access these arrays via their names? I'm pretty sure that common std::vector< std::vector<double> > would suffice here.

Comments

0

Here's 3 solutions: the first is closest to your example code, the second is an improvement in order to be able to correctly retrieve the array elements within bounds, and the third is the reason why you are better served with vectors.

Solution 1:

It looks like you want your arrays to have names that are distinguishable by your loop iterator. Like Joe said, you could have an array of an array, so the inner arrays will be named array[0], array[1], ..., array[n - 1]. This will be achieved by using a pointer to pointer to double. Each of the inner pointers will be used to dynamically allocate arrays of double. Don't forget to delete the dynamically allocated memory.

#include <iostream>
int main()
{
    unsigned int n;
    std::cout << "Enter number of arrays: ";
    std::cin >> n;
    double** array = new double*[n];

    for (int i = 0; i < n; ++i)
    {
        unsigned int size;
        std::cout << "Enter size of array " << i << ": ";
        std::cin >> size;
        array[i] = new double[size];
        for (int j = 0; j < size; ++j)
        {
            int element;
            std::cout << "Enter element " << j << " of array " << i << ": ";
            std::cin >> element;
            array[i][j] = element;
        }
    }

    for (int i = 0; i < n; ++i)
    {
        delete [] array[i];
    }
    delete[] array;
    return 0;
}

Solution 2:

However, with the above code, you will have trouble accessing the elements of each inner array. Unless you memorized the size of each inner array you create with this, you might access something out of bounds. Therefore, an update to this code would be to add yet another array, let's call it sizeOfInnerArrays, where each of its element i keeps track of the size of inner array array[i]. Here's the update:

    #include <iostream>
    int main()
    {
        unsigned int n;
        std::cout << "Enter number of arrays: ";
        std::cin >> n;
        double** array = new double*[n];
        unsigned int* sizeOfInnerArrays = new unsigned int[n];

        for (int i = 0; i < n; ++i)
        {
            std::cout << "Enter size of array " << i << ": ";
            std::cin >> sizeOfInnerArrays[i];
            array[i] = new double[sizeOfInnerArrays[i]];
            for (int j = 0; j < sizeOfInnerArrays[i]; ++j)
            {
                int element;
                std::cout << "Enter element " << j << " of array " << i << ": ";
                std::cin >> element;
                array[i][j] = element;
            }
        }

        //prints out each array as curly-brace enclosed sets of doubles
        for (int i = 0; i < n; ++i)
        {
            std::cout << "{";
            for (int j = 0; j < sizeOfInnerArrays[i] - 1; ++j)
            {
                std::cout << array[i][j] << ", ";
            }
            std::cout << array[i][sizeOfInnerArrays[i] - 1] << "}" << std::endl;
        }

        // free dynamically allocated memory
        for (int i = 0; i < n; ++i)
        {
            delete [] array[i];
        }
        delete[] array;
        delete[] sizeOfInnerArrays;

        return 0;
    }

Solution 3:

However, that is too complicated, so you are better off using a container, like vector, as Joe suggested, whose data member keeps track of its size.

#include <iostream>
#include <vector>

int main()
{
    unsigned int n;
    std::cout << "Enter number of vectors: ";
    std::cin >> n;
    std::vector<std::vector<double> > myVec;
    // ^ space between closing angle brackets not needed
    //   if using C++11 conforming compiler

    for (int i = 0; i < n; ++i)
    {
        unsigned int size;
        std::cout << "Enter size of vector " << i << ": ";
        std::cin >> size;
        std::vector<double> temp;
        temp.reserve(size);
        for (int j = 0; j < size; ++j)
        {   
            double value;
            std::cout << "Enter next value of vector " << i << ": ";
            std::cin >> value;
            temp.push_back(value);
        }
        myVec.push_back(temp);
    }

    for (int i = 0; i < myVec.size(); ++i)
    {
        std::cout << "{";
        for (int j = 0; j < myVec.at(i).size() - 1; ++j)
        {
            std::cout << myVec.at(i).at(j) << ", ";
        }
        std::cout << myVec.at(i).back() << "}" << std::endl;
    }

    return 0;
}

2 Comments

new[] and delete[] are sooo last century
I used regular arrays first because that's closest to OP's example code. I made an edit to add extra solutions. In the second solution, I added an array that keeps track of the other arrays' sizes in order to retrieve elements within bounds. This sets up the incentive to use vectors in the third solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.