Using a pre-computed array in another function?
Richard Damon
Richard at Damon-Family.org
Sun Jul 8 19:38:27 CEST 2012
On 7/8/12 12:38 AM, Alasdair McAndrew wrote:
> Hi there,
>
> I have a pre-computed array, which I'd like to use in another function.
> This program shows the sort of thing I'm trying to do - I've created an
> array A in the main program, and I need to use those values in my function
> "mpz_myfun". However, this gives me a segmentation fault.
>
> Any ideas as to how I can fix this up so it works? Oh, I'm using gcc
> version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3) and gmp 5.0.5.
>
> Thanks,
> Alasdair
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <gmp.h>
>
> mpz_t b,r,j,p,T,n,out;
> mpz_t *A;
>
> void mpz_myfun(mpz_t r,mpz_t m)
> {
> gmp_printf("Zd\n",A[100]);
> mpz_t tmp;
> mpz_init(tmp);
> mpz_and(tmp,m,T);
> mpz_set(r,A[mpz_get_ui(tmp)]);
> mpz_clear (tmp);
> }
>
> int main(int argc, char *argv[])
> {
> mpz_init_set_ui(b,7);
> mpz_init_set_ui(T,65535);
> mpz_init_set_ui(p,0x7FFFFFFF);
> mpz_init(j);
> mpz_t *A = malloc(65536*sizeof(mpz_t));
> for (unsigned long i=0; i<65536; i++)
> {
> mpz_powm_ui(A[i],b,i,p);
> }
>
> mpz_init_set_str(n,argv[1],10);
> mpz_init(out);
>
> mpz_myfun(out,n);
>
> gmp_printf("%ZD\n",out);
>
> return 0;
> }
> _______________________________________________
> gmp-discuss mailing list
> gmp-discuss at gmplib.org
> https://gmplib.org/mailman/listinfo/gmp-discuss
>
You are declaring TWO different variables with the name A, one as a
global, and one as a local in main, and it is the local that you are
assigning the memory to, so myfun is seeing an A still at address 0.
Change the line in main to just
A=malloc(65536(sizeof(mpz_t));
--
Richard Damon
More information about the gmp-discuss
mailing list