views:

55

answers:

1

Hello, I'm working on some project where I use the type mpz_t from the GMP C library. I have some problems passing an array of structures (containing mpz_ts) adress to a function : I wille try to explain my problem with some code.

So here is the structure :

 struct mpz_t2{
    mpz_t a;
    mpz_t b;
  };
  typedef struct mpz_t2 *mpz_t2;


void
mpz_t2_init(mpz_t2 *mpz_t2)
{
  mpz_init(mpz_t2->a);
  mpz_init(mpz_t2->b);
}


void
petit_test(mpz_t2 *test[])
{
  printf("entering petit test function\n");
  for (int i=0; i < 4; i++)
  {
    gmp_printf("test[%d]->a = %Zd and test[%d]->b = %Zd\n", test[i]->a, test[i]->b);
  }
}



/* IN MAIN FUNCTION */

mpz_t2 *test = malloc(4 * sizeof(mpz_t2 *));

  for (int i=0; i < 4; i++)
    {
      mpz_t2_init(&test[i]); // if I pass test[i] : compiler error
      mpz_set_ui(test[i].a, i); //if test[i]->a compiler error
      mpz_set_ui(test[i].b, i*10); //same problem
      gmp_printf("%Zd\n", test[i].b); //prints correct result
    } 
  petit_test(test);

The programm prints the expected result (in main) but after entering the petit_test function produces a segmentation fault error.

I would need to edit the mpz_t2 structure array in petit_test. I tried some other ways allocating and passing the array to the function but I didn't manage to get this right.

If someone has a solution to this problem, I would be very thankfull!

Regards, jérôme.

A: 

In the code that you have displayed, you are allocating memory for the array of pointers, but you are not initializing the pointers to point to anything. You need to allocate some instances of mpz_t2, and then assign your pointers to point to them.

---------------edited here---------------

It looks like this is what you're trying to do:

mpz_t2 **test = (mpz_t2**)malloc(4 * sizeof(mpz_t2 *));

for (int i=0; i < 4; i++)
{
    test[i] = (mpz_t2*)malloc(sizeof(mpz_t2));
    mpz_t2_init(test[i]); 
    ...
} 
petit_test(test);
jwismar
sorry i forgot to add the initialisation function :void mpz_t2_init(mpz_t2 *mpz_t2); which uses gmp library mpz_init function on each member of the structure.
jerome
You still haven't allocated any instances of mpz_t2.... I'll add something to my answer.
jwismar
This works, many thanks !!!
jerome