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

标签 c pointers casting

我正在生成动态大小的数组。我展示的代码部分是按照它的方式获取数组的值,并且它有效。

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

如何正确编写类似的代码?

示例:*(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");
    }

最佳答案

它做了什么:

&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 的表示,这很有用:

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 表示的位。

关于c - *(int*)变量是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858717/

相关文章:

C++ 将模板参数转换为其无符号版本

c++ - 使用 c-preprocessor 自动生成函数转发器

c++ - 一行中的最后一个数组元素和下一行中具有相同指针的第一个元素

c - 在 C 中通过引用传递数组

c - 是否正在评估指向 undefined object 存储之外的指针?

c - 简单的C指针混淆

asp.net - 在 VB.Net 中将字符串转换为 Guid

C++ 类型转换错误

c - 我如何找到我正在运行的 CPU/内核?

C 编程 - K&R 示例 1.5.2 - 修改后的程序未按预期运行