Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a valid method of creating an array in C?

int threads = 5;

pthread_t * thread = malloc(sizeof(pthread_t)*threads);

            for (i = 0; i < threads; i++){
                int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);}

I'm not in a position to run the code right now. But I saw this as part of an online example and was a little confused by the total lack of square brackets. I'm not great with C.

So does this work for creating an array of threads?

like image 586
temporary_user_name Avatar asked Jan 18 '26 06:01

temporary_user_name


1 Answers

Yes.

thread is pointing at a block of memory allocated by malloc that is large enough to hold threads pthread_t objects.

An array of threads pthread_t objects can be represented in exactly this way.

like image 118
dma Avatar answered Jan 20 '26 21:01

dma