我正在生成动态大小的数组。我展示的代码部分是按照它的方式获取数组的值,并且它有效。
问题是我不知道这是如何工作的。我不明白为什么 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/