ddschmitz
ddschmitz

Reputation: 538

How to malloc an array inside a struct

I need to pass a structure containing parameters to some threads. One of the parameters is a very large array. I am trying to do what I have done previously where I create the array on the heap using malloc but I can't seem to figure out how to do it with a struct. Then what I'll do is memcpy a different array into the struct array.

#define LIMIT 100000           //Size of seive
#define THNUMS 3               //Number of threads

struct ThreadParams
{ 
    int id;                       // id
    int low;                      // start
    int high;                     // end
    int *structprimes;            // each thread's seive
    structprimes = malloc(sizeof(int)*LIMIT);
 };

Then I create a sieve and then need to copy this sieve to the structs array. I was able to do this with a smaller arrays on the stack with something like this (not complete):

struct ThreadParams ptharg[THNUMS];

memcpy(ptharg[i].structprimes, primes, sizeof(int)*LIMIT);

pthread_create(&tid, NULL, Work, (void*)&ptharg[i])

Hopefully this makes sense? What I'm trying to do is create an array inside a struct using malloc if that's at all possible?

EDIT AND SOLUTION: What I ended up doing was making the struct like this:

struct ThreadParams
{ 
    int id;                       // id
    int low;                      // start
    int high;                     // end
    int *structprimes;     // each thread's seive
};

and then in main() assigning the memory to the pointer with malloc:

for (a = 0; a < THNUMS; a++) 
{
    ptharg[a].structprimes = malloc(sizeof(int)*LIMIT);
}

Upvotes: 1

Views: 2992

Answers (1)

kaylum
kaylum

Reputation: 14046

In C it is not possible to have statements inside struct definitions. Instead you need to declare the variable then initialise the variable, including any dynamic memory. For example:

struct ThreadParams ptharg[THNUMS];
int ix;

for (ix = 0; ix < THNUMS; ix++) {
    ptharg[ix].structprimes = malloc(sizeof(int)*LIMIT);
    if (!ptharg[ix].structprimes) {
        /* error handling goes here */
    }
}

Alternatively, the array can be declared statically in the structure. For example:

struct ThreadParams
{ 
    int id;                       // id
    int low;                      // start
    int high;                     // end
    int structprimes[LIMIT];            // each thread's seive
 };

However there is a second possible problem in your approach. You have not shown where struct ThreadParams ptharg[THNUMS]; is located. But if it is inside any function apart from main then it cannot be passed as a data argument to child threads because it would be an automatic variable that goes out of scope when that function exits.

Upvotes: 3

Related Questions