I am trying to perform numerical analysis and optimization in C using the functions made available via the R API. I am making use of the functions mentioned in the "6.7 Numerical analysis subroutines" (https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Numerical-analysis-subroutines) and "6.8 Optimization" (https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Optimization) sections of the "Writing R Extensions" document.
Everything is working fine except the optimization part. I do not get any error while compiling the code into a .exe file. But when I run the generated .exe file, it shuts down instantly despite adding getch() command. The complete code is given below -
#include <stdio.h>
#include <stdlib.h>
#include <Rmath.h>
#include "R_ext/Applic.h"
#include <conio.h>
typedef struct
{
double *X;
int n;
} data;
double myfunc(int m, double *par, void *ex)
{
data *input = ex;
double *X = input->X;
int n = input->n;
double mu = par[0];
double sum = 0.0;
int i;
for (i=0; i<n; i++)
{
double t = X[i] - mu;
sum += t*t;
}
return sum;
}
int main()
{
printf("%lf\n",norm_rand());
printf("%lf\n\n",unif_rand());
double z = 10;
double mean = 0;
double sigma = 1;
int give_log = 1;
double result;
result = dnorm(z,mean,sigma,give_log);
printf("%lf\n\n",result);
printf("%lf\n\n",gammafn(z));
int i,n=1, trace=1, maxit=100, fail, fncount;
double *par, abstol=0.0001, intol=.0001, alpha=1, beta=.5, gamma=2, *xin, *x, Fmin;
data ex;
par=malloc(n*sizeof(double));
xin=malloc(n*sizeof(double));
x=malloc(n*sizeof(double));
par[0]=5;
xin[0]=5;
ex.n=5;
ex.X=malloc(ex.n*sizeof(double));
for(i=0;i<ex.n;i++) ex.X[i]=i;
nmmin(n,xin,x,&Fmin,myfunc,&fail,abstol,intol,&ex,alpha,beta,gamma,trace,&fncount,maxit);
free(par);
free(x);
free(xin);
free(ex.X);
getch();
return 0;
}
Here is the output just before shutting down -

I am definitely making a mistake somewhere but don't know exactly where. Also, how can I obtain the output from the nmmin() function as its return type is void?