简体   繁体   中英

Changing the size of an array inside of a struct C++

I have a structure that is shown below.

struct thread_data{
   int staringPoint;
   int endingPoint;
   double query[];
}; 

The user enters a number and I need that entered in number to be the size of the array. Is there any way to either allocate memory for the array or set the size of that array after the user enters the number?

I tried to do it like this:

int userNumber = 10;
struct thread_data newThreads[5];


for(int i=0; i < 5;i++){
    newThreads[i].query = new double[userNumber];
}

but I get this error message:
array type 'double []' is not assignable

An easy solution would be:

struct thread_data{
    int staringPoint;
    int endingPoint;
    std::vector<double> query;
}; 

// ...

for(int i=0; i < 5;i++)
    newThreads[i].query.resize(userNumber);

You allocate it right but change double query[]; to double *query;

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