开发者

passing an array of structures (containing two mpz_t numbers) to a function

开发者 https://www.devze.com 2022-12-23 18:19 出处:网络
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'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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消