TriposG
TriposG

Reputation: 113

Allocating memory to an array in a struct

I have defined a struct as below

struct Invariant
{
    int *           numberOfConstPi;        //  Saves the number of constant Pi in each kernel


    Invariant *     next;
};

I then modified it later in the code as

invariant->numberOfConstPi = (int *)calloc(invariant->numberOfUniqueKernels, sizeof(int));
invariant->numberOfConstPi[countKernel] = numberOfConstPi;

Where countKernel is an iterator and numberOfConstPi is a variable.

Is this the correct way? When I run the code I'm getting segmentation errors.

But when I instead defined the array as

int * hello = (int *)calloc(invariant->numberOfUniqueKernels, sizeof(int));

and

hello[countKernel] = numberOfConstPi;

It works perfectly fine.

Kindly ignore the int variable numerOfUniqueKernels. It's just a number which I deleted from the Struct(to make the struct look simpler for the question)

Upvotes: 1

Views: 100

Answers (1)

myradio
myradio

Reputation: 1775

You don't show much code, but as for your question regarding this piece of code,

invariant->numberOfConstPi = (int *)calloc(invariant->numberOfUniqueKernels, sizeof(int));
invariant->numberOfConstPi[countKernel] = numberOfConstPi;

Is this the correct way?

I can say, this is a valid way to do it. But you don't show much code and you say that you are running into segfault errors. I would guess that maybe you are not allocating memory for the pointer to struct?

You should have something like,

Invariant *invariant = malloc(sizeof*invariant);

Upvotes: 4

Related Questions