Could anyone help?
The string I use to compile this program and the error message:Code:#include <stdlib.h> #include <stdio.h> #include <gmp.h> mpz_t fact (int num) { int i; mpz_t result; mpz_init (result); mpz_set_ui (result, 1); for (i = 1 ; i <= num ; i++) mpz_mul_ui (result, result, i); return (result); } int main (int argc, char **argv) { int num; mpz_t ans; mpz_init (ans); if (argc < 2) { fprintf (stdout, "Usage: %s <Integer>\n", argv[0]); exit (1); } num = atoi (argv[1]); ans = fact (num); gmp_printf ("%Zd\n", ans); return (0); }
Does anyone know what the problem is and would care to explain it to me?[vince@vincent: ~/prog/cpp]% g++ -O6 -fomit-frame-pointer -lgmp fact.cpp -o fact fact.cpp:7: `fact' declared as function returning an array fact.cpp: In function `int fact(int)':
fact.cpp:18: return to `int' from `__mpz_struct *' lacks a cast
fact.cpp: In function `int main(int, char **)':
fact.cpp:38: incompatible types in assignment of `int' to `__mpz_struct[1]'
fact.cpp:40: implicit declaration of function `int gmp_printf(...)'
[vince@vincent: ~/prog/cpp]%
Could anyone help?
From http://www.gnu.org/manual/gmp-3.1.1/...de/gmp_12.html
In C++ a function cannot return an array "by value".mpz_t is actually implemented as a one-element array of a certain structure type. This is why using it to declare a variable gives an object with the fields GMP needs, but then using it as a parameter passes a pointer to the object.
Code:#include <stdlib.h> #include <stdio.h> #include <gmp.h> void fact (mpz_t *result, int num) { int i; mpz_set_ui (*result, 1); for (i = 1 ; i <= num ; i++) mpz_mul_ui (*result, *result, i); } int main (int argc, char **argv) { int num; mpz_t ans; int gmp_fprintf; mpz_init (ans); if (argc < 2) { fprintf (stdout, "Usage: %s <Integer>\n", argv[0]); exit (1); } num = atoi (argv[1]); fact (&ans, num); gmp_printf ("%Zd\n", ans); return (0); }gcc -lgmp -O6 -fomit-frame-pointer fact.c -o fact./fact 65536 22.79s user 0.10s system 99% cpu 22.941 total
Bookmarks