1

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)

TriposG
  • 103
  • 1
  • 2
  • 11
  • You don't show enough code to really know. Also, you need to check the return value of `calloc` to ensure that it's not `NULL`. Also, [don't cast the return value of the allocation functions](https://stackoverflow.com/a/605858/5567382). – Thomas Jager Aug 22 '19 at 15:01
  • Its a part of a compiler and hence there is a lot of code – TriposG Aug 22 '19 at 15:43

1 Answers1

4

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);
myradio
  • 1,703
  • 1
  • 15
  • 25