HelpNeeder
HelpNeeder

Reputation: 6490

What does *(int*)&variable means?

I am generating arrays which are dynamic size. The part of the code that I am showing is grabbing value of the array the way it does, and it works.

The problem is I have no idea how this work. I don't see why both cast and pre-cast have pointer in it?

How to code something similar correctly?

Example: *(double*)&j;

I also noticed that *(int*)&column_sum[i] + 1; won't add the 1 to the result. Also I have no idea why...

    double val = 1000 * multiplier;
    double *column_sum = malloc(val * sizeof *column_sum);
    double *p = malloc(val * val * sizeof *p);
    printf("Rows/Columns: %.0f", val);

    for (i = 0; i < val; i++){
        column_sum[i] = 0.0;
        for (j = 0; j < val; j++){
            int index = i * (int)val + j;
            p[index] = *(double*)&j; // here
            int offsetI = *(int*)&column_sum[i] + 1; // here
            int offsetJ = *(int*)&p[index] + 1; // here
            printf("%d->", offsetI);
            printf("%d,", offsetJ);
        }
        printf("\n");
    }

Upvotes: 1

Views: 5357

Answers (1)

alkino
alkino

Reputation: 913

What does it do:

&var // get the pointer of the variable
(type*)&var // cast the pointer to an other pointer type
*(type*)&var // Dereferencing the casted pointer so "interpret" the variable as a "type"

What is important here, is that it is interpret and not cast.

We can see the difference in this example:

float a = 0.5;
int b = (int)a;
int c = *(int*)&a;

printf("%f %08x %08x\n", a, b, c);

// Output:
// 0.500000 00000000 3f000000
// 3f000000 is the way 0.5 is encoding following standard IEEE 754

It's usefull if you want to work on representation of floats for example:

float a = 1.5;
int b = *(int*)&a;
b &= 0xF;
a = *(float*)&b;

For example it's the reason of the use of this syntax here: https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code, for manipulating bit of representation of double.

Upvotes: 3

Related Questions