0

I have a global array in my program and I want to be able to change it's size at least once in the beginning using a function. Basically like this:

pthread_t threadsArray[10]; //default size: 10

void SetMaxThreads(unsigned int count) {
    pthread_t threadsArray[count];
}

What would you suggest me to do? How could I accomplish this?

2 Answers 2

3

I would suggest to use standard container std::vector instead of the array.

For example

std::vector<pthread_t> threadsArray( 10 ); //default size: 10

void SetMaxThreads(unsigned int count) {
    threadsArray.resize( count );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hm, I've never worked with vectors, could you provide an example? Would I have to change my code a lot?
0

You could declare a dynamic array. This can be done with two different ways. You can either use std::vector, or you can use pointers.Vector Documentation. Example using pointers:

pthread_t *threadsArray; // no default size

void SetMaxThreads(unsigned int count) {
   delete [] threadsArray;
   threadsArray = new pthread_t[count];
}

Edit: as some comments pointed out, it is safer to use std::unique_ptr<pthread_t[]> instead of array pointers.std::unique_ptr Documentation

2 Comments

std::unique_ptr<pthread_t[]> would be better than raw owning pointer.
This is not exception safe (if new throws, threadsArray will not point to valid memory). There is a reason why the use of raw pointers is discouraged...

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.