C-like pointer casting
Feb 19, 2013 at 3:11pm Feb 19, 2013 at 3:11pm UTC
Hello,
I am trying to understand some GSL routines and I have a hard time figuring out what the following line of code does
1 2
void * p
struct powell_params* params = *(struct powell_params*)p;
As I understand it, the bit
casts void pointer
p
to a pointer of type
struct powell_params*
. Then the outer asterisk operator in
*(struct powell_params*)p
dereferences this pointer. But then why is this dereferenced pointer being assigned to a pointer of type
struct powell_params*
in the original line?
Cheers,
Little
Feb 19, 2013 at 3:35pm Feb 19, 2013 at 3:35pm UTC
You're right. It doesn't make sense. It's assigning a non-pointer to a pointer which shouldn't work.
I don't think this would compile.
EDIT:
And in fact, it doesn't compile. I get a compiler error as expected:
1 2 3 4 5 6 7 8 9 10 11 12
struct powell_params
{
int foo;
};
int main()
{
powell_params obj;
void * p = &obj;
struct powell_params* params = *(struct powell_params*)p;
}
error C2440: 'initializing' : cannot convert from 'powell_params' to 'powell_params *'
Last edited on Feb 19, 2013 at 3:37pm Feb 19, 2013 at 3:37pm UTC
Feb 19, 2013 at 3:57pm Feb 19, 2013 at 3:57pm UTC
Thank you Disch for your reply. I want to use GSL's multidimensional root finding routine. The offending line comes from an example showing how a system of two nonlinear equations is described:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
struct powell_params { double A; };
int
powell (gsl_vector * x, void * p, gsl_vector * f) {
struct powell_params * params
= *(struct powell_params *)p;
const double A = (params->A);
const double x0 = gsl_vector_get(x,0);
const double x1 = gsl_vector_get(x,1);
gsl_vector_set (f, 0, A * x0 * x1 - 1);
gsl_vector_set (f, 1, (exp(-x0) + exp(-x1)
- (1.0 + 1.0/A)));
return GSL_SUCCESS
}
gsl_multiroot_function F;
struct powell_params params = { 10000.0 };
F.f = &powell;
F.n = 2;
F.params = ¶ms;
It all makes sense to me aside from the de-referencing :(
I will try to compile this and see where I get
Cheers,
Little
Feb 19, 2013 at 5:09pm Feb 19, 2013 at 5:09pm UTC
There are several error in the GSL documentation. I compiled this without a hitch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
struct powell_params { double A; };
int
powell (const gsl_vector* x, void * p, gsl_vector* f) {
struct powell_params* params
= (struct powell_params*)p;
const double A = (params->A);
const double x0 = gsl_vector_get(x,0);
const double x1 = gsl_vector_get(x,1);
gsl_vector_set (f, 0, A * x0 * x1 - 1);
gsl_vector_set (f, 1, (exp(-x0) + exp(-x1)
- (1.0 + 1.0/A)));
return GSL_SUCCESS;
}
gsl_multiroot_function F;
struct powell_params params = { 10000.0 };
F.f = &powell;
F.n = 2;
F.params = ¶ms;
Case closed
Little
Topic archived. No new replies allowed.