*(int *)&变量是什么意思?

时间:2014-09-15 23:59:29

标签: c pointers casting

我正在生成动态大小的数组。我展示的代码部分是以它的方式获取数组的值,并且它可以工作。

问题是我不知道这是如何工作的。我不明白为什么演员和预演都有指针?

如何正确编码类似的东西?

示例:*(double*)&j;

我还注意到*(int*)&column_sum[i] + 1;不会将1添加到结果中。我也不知道为什么......

    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");
    }

1 个答案:

答案 0 :(得分:2)

它做了什么:

&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"

重要的是,它是interpret而不是cast

我们可以看到这个例子的不同之处:

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

如果您想处理浮点数的表示,例如:

,这是有用的
float a = 1.5;
int b = *(int*)&a;
b &= 0xF;
a = *(float*)&b;

例如,这里使用此语法的原因是:https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code,用于操纵double的表示位。

相关问题