I am getting a segfault when accessing anything within the point
struct below from within another function. The printf
before Calculate_values(&s)
works as expected (along with other lines to test accessing the point struct), but a segmentation fault is caused when within the function.
Could this be a problem with pointers? log1
line is never reached, ruling out the call to Rpv function.
Code:
typedef struct point
{
double *coord;
double value;
} point;
typedef struct state
{
void (*function)(point*, int);
point *points; // p0, p1, p2, ...
int dimentions; // number of points is always dimentions + 1
} state;
void Rpv(point *x, int dimentions)
{
x->value = 0;
for (int d = 0; d < dimentions - 1; d++)
x->value += 100 * pow(x->coord[d + 1] - x->coord[d] * x->coord[d], 2) +
pow(1 - x->coord[d], 2);
}
void Calculate_values(state *s)
{
for (int n = 0; n <= s->dimentions; n++)
{
printf("log (n: %d)\n", n);
point p = s->points[0];
printf("log1");
s->function(p, s->dimentions);
printf("log2\n");
}
}
point minimisation(void (*function)(point*, int),
point initial_points[],
int dimentions)
{
state s;
s.points = initial_points;
s.dimentions = dimentions;
printf("[%lf, %lf] -> %lf\n", s.points[0].coord[0], s.points[0].coord[1], s.points[0].value);
Calculate_values(&s);
// ... more code
return s.points[0];
}
int main()
{
point initial_points[] = {
{(double[]){3, 1}, 0}, // p1
{(double[]){2, 0}, 0}, // p2
{(double[]){0, 2}, 0} // p3
};
point minimum = minimisation(Rpv, initial_points, 2);
printf("minimum = %lf, @ (%lf, %lf)\n", minimum.value, minimum.coord[0], minimum.coord[1]);
return 0;
}
Output seen:
[3.000000, 1.000000] -> 0.000000
log (n: 0)
Segmentation fault (core dumped)