C-like pointer casting

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

 
(struct powell_params*)p


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

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
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 = &params;


It all makes sense to me aside from the de-referencing :(
I will try to compile this and see where I get

Cheers,
Little
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 = &params;


Case closed
Little
Topic archived. No new replies allowed.