C中的数组索引是否必须是整数?它可以是一个浮点吗?

chu*_*tsu 2 c arrays floating-point integer

正如标题所暗示的......我需要使用浮点作为数组索引,但是GCC编译器会抛出错误抱怨.

基本上我有一个数学函数说F(x,t),其中函数有变量x和t.我遇到的问题是我试图在float类型中增加x和t,这样我就可以在不同的x和t处计算函数的不同值.所以我自然会有两个for循环:

for (x = x_min; x < x_max; x += dx) {
    for (t = t_min; t < t_min; t += dt) {
        f[x][t] = 10*x + 10*t; // Over simplified.. but you get the idea
    }
}

// And then perform some fourier transform
fft(f[x][t], 256, 1);
Run Code Online (Sandbox Code Playgroud)

所以,这就是为什么我想知道是否有可能将浮点作为数组索引.

Ed *_* S. 5

是的,它必须是一个整数,因为您实际上是在执行指针算术运算,其中&array[0]是指向数组开头的指针(好吧,从技术上讲,它必须是一个整数,因为这是规范所说的,但这就是原因)。

在这种情况下,从基指针向上移动对象大小的一小部分是没有意义的。您几乎可以保证不会指向元素的开头。

这样看:

int array[10] = { 0 };

// analagous to *(array + 5), where '5' is 
// offsetting the pointer by sizeof(int) * 5 bytes   
// If you were able to add 5.5 to the base address 
// the value assigned to 'i' below would be interpreted as
// the four bytes following *(array + 5.5), i.e., garbage data.
int i = array[5];  
Run Code Online (Sandbox Code Playgroud)

由于这首先让我觉得这是一个奇怪的问题,也许您可​​以向我们提供有关您实际尝试完成的工作而不是您提出的解决方案的更多信息?在这种情况下,我们可能会为您提供更多有用的答案。


R..*_*R.. 5

如果您只是将整数存储在浮点变量中,那么转换或以其他方式将值转换为整数类型应该可以正常工作.例如:

array[(int)x] = y;
Run Code Online (Sandbox Code Playgroud)

如果你真的想用非整数索引索引一个数组,你将不得不设计一个更高级别的数据结构,从时间效率属性的角度来看,它可能不是一个"数组".