1+ #include <stdio.h>
2+ #include <stdlib.h>
13#include <string.h>
24#include <SWI-Prolog.h>
35
4- #define MAXLINE 1024
5-
66int
77main (int argc , char * * argv )
8- { char expression [MAXLINE ];
9- char * e = expression ;
8+ { char * expression ;
109 char * program = argv [0 ];
11- char * plav [2 ];
12- int n ;
1310
14- /* combine all the arguments in a single string */
11+ if ( argc < 2 )
12+ { fprintf (stderr , "Usage: %s expression\n" , program );
13+ exit (1 );
14+ }
15+
16+ /* Determine length of joined arguments */
17+ size_t len = 1 + argc - 2 ;
18+ for (int n = 1 ; n < argc ; n ++ )
19+ len += strlen (argv [n ]);
20+ if ( !(expression = malloc (len )) ) // freed on exit
21+ { perror ("allocate" );
22+ exit (1 );
23+ }
1524
16- for (n = 1 ; n < argc ; n ++ )
25+ /* combine all the arguments as a single string */
26+ char * e = expression ;
27+ for (int n = 1 ; n < argc ; n ++ )
1728 { if ( n != 1 )
1829 * e ++ = ' ' ;
1930 strcpy (e , argv [n ]);
@@ -22,24 +33,27 @@ main(int argc, char **argv)
2233
2334 /* make the argument vector for Prolog */
2435
25- plav [0 ] = program ;
26- plav [1 ] = NULL ;
36+ int plac = 0 ;
37+ char * plav [2 ];
38+ plav [plac ++ ] = program ;
39+ plav [plac ] = NULL ;
2740
2841 /* initialise Prolog */
2942
30- if ( !PL_initialise (1 , plav ) )
43+ if ( !PL_initialise (plac , plav ) )
3144 PL_halt (1 );
3245
3346 /* Lookup calc/1 and make the arguments and call */
3447
3548 { predicate_t pred = PL_predicate ("calc" , 1 , "user" );
36- term_t h0 = PL_new_term_refs ( 1 ) ;
37- int rval ;
49+ bool rc ;
50+ term_t h0 ;
3851
39- PL_put_atom_chars (h0 , expression );
40- rval = PL_call_predicate (NULL , PL_Q_NORMAL , pred , h0 );
52+ rc = ( (h0 = PL_new_term_refs (1 )) &&
53+ PL_unify_chars (h0 , PL_STRING |REP_MB , (size_t )-1 , expression ) &&
54+ PL_call_predicate (NULL , PL_Q_NORMAL , pred , h0 ) );
4155
42- PL_halt (rval ? 0 : 1 );
56+ PL_halt (! rc );
4357 }
4458
4559 return 0 ;
0 commit comments