简体   繁体   中英

Dynamic array C++

I want to create arrays dynamically within the for loop. I have something like bellow:

for (int i = 0; i < line; i++){

complex* in[i] = new complex[8];

}

complex is a user defined data type. Is there any way to do the above operation. I am getting error for that. I want to create few pointers for more than one array (can't say how many arrays I will need) where each pointer will point to a particular array.

Thanks in advance.

If your 'inner' arrays are all 8 elements each, you can use this approach for a dynamically resizable array of complex arrays of 8 elements:

std::vector<std::array<complex, 8> > c(line);
// new and delete are not needed here

You could of course substitute std::vector for std::array in this case -- std::array may not be available depending on the library you're using.

std::array is a little more exact than std::vector when the element count is invariant. Thus, std::array can make a ton of optimizations std::vector cannot. How that affects your program may or may not be measurable.

The good thing about this is that the library implementations are well tested, will insulate you from and detect some usage errors.

The construct complex *in[i] = ... does not make sense. You cannot declare the elements of an array one after the other. You have to declare the entire array before the loop.

Ie, something like the following

complex *in[MAX_LINES];
// or you can allocate in[] dynamically:
// complex *in[] = new (complex*)[line];

for (int i = 0; i < line; i++){
    in[i] = new complex[8];
}

Of course, unless you specifically need C-style arrays (for example - for interfacing with C code), it is probably better to use C++ vectors/arrays (as Justin had shown in another answer).

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