简体   繁体   中英

confusion about arrays

I have an array like that:

int sizes[5] = {1,2,3,4,5};

I want to have 5 different arrays by using the array above. Because I want each of my arrays to have the size of sizes[i] (0 <= i < 5) . How can I do that? The more I ponder upon this, the more I get confused. Do I have to use multidimensional arrays or just a simpler solution? Thanks in advance.

I demand STL in the thread!

std::vector<int> arrays[5];
for (i = 0; i < 5; ++i)
    arrays[i].resize(sizes[i]);

As I understood you question, you need array of arrays which length can be in range [0, 5] (with variable length).

So there are a lot of choices, I shall offer you 2 of them:

  1. As you marked your question with C++ tag I offer you to refer to STL , which offer a lot of convenient containers and one of them is std::vector which is dynamic array (size of it can vary).

  2. If you fill convenient with C , then you can use an array of pointers , each of them will be pointer on array.

Simple, you just need dynamic memory allocation:

int sizes = {1, 2, 3, 4, 5};
int **arrays;
int i;

arrays = new int*[5];
for(i = 0; i < 5; i++)
    arrays[i] = new int[sizes[i]]

This is a simple thing to start with, but in real life the STL libraries are much more useful. In this code the memory is dynamically allocated, but not released. This can result into a memory leak. Using std::vector from STL library will save you from the hassle, and provide a easier way.

@Mikhail has shown a good demonstration of using vector s below.

to answer the question, yes you do need a multidimensional array in the most efficient case. An array of arrays, while the elements are dynamically allocated(considering the number of arrays you specified is constant).

int *Array[5];
for(int i = 0; i < sizes; i++)
{
    Array[i] = new int[sizes[i]];
}

you now have 5 dynamically allocated arrays ranging from size 0 to size 5.

You have to use a dynamic allocation, something like this:

int *arrays[5];
int i = 0;
int sizes[] = {1,2,3,4,5};
for(i = 0; i < 5; i++)
{
    arrays[i] = (int *)malloc(sizes[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM