2015-07-03 18 views
4

我想了解在使用浮点值对数组进行索引时会发生什么。C++ - 当您通过浮点数组索引数据会发生什么?

此链接:Float Values as an index in an Array in C++

不回答我的问题,因为它指出了浮动应四舍五入到整数。然而,在我试图评估的代码,这个答案是没有意义的,因为该指数值将永远只能是0或1

我试图解决张贴任天堂编码的挑战。为了解决这个问题,存在一个陈旧的陈述,它使用一个长而复杂的按位表达式来按位分配到一个数组中。

阵列被声明为指针

unsigned int* b = new unsigned int[size/16]; // <- output tab

然后它分配0的每个元素

for (int i = 0; i < size/16; i++) { // Write size/16 zeros to b 
    b[i] = 0; 
} 

这里的语句的开头。

b[(i + j)/32] ^= // some crazy bitwise expression

嵌套的内部上面的位于for循环。

我在这里节约了大量的代码,因为我想尽可能多的这个问题的解决我自己的地。但我想知道是否有这种情况,你是否想要像这样迭代数组。

必须有比浮动只是自动转换成一整型更多的东西。这里还有更多的事情要做。

+1

A [数字转换(http://en.cppreference.com/w/cpp/language/implicit_cast#Numeric_conversions)发生,从浮点型到整型。 –

+1

不是'int/16'仍然是'int',而不是'float'。 – Jarod42

+0

@JoachimPileborg发生编译错误 –

回答

8

没有float在这儿。 size是一个整数,和16是一个整数,并因此size/16是一个整数,以及。

整数除法向零调整,所以如果size[0,16),那么size/16 == 0。如果size[16,32)中,则size/16 == 1等等。并且如果size(-16, 0],那么size/16 == 0也是如此。

[x,y)xy“半开”间隔:那就是,它包含xy之间的每一个数字,而且它包括x但不包括y

+0

谢谢,这很有道理。显然,我正在以比实际更难的方式来看待问题,并且由于过度思考而忽略了初学者的东西。 –

2

要回答的问题标题:

#include <stdio.h> 
int main(int argc, char** argv) { 
    int x[5]; 

    int i; 
    for (i = 0; i < 5; ++i) 
    x[i] = i; 


    x[2.5] = 10; 

    for (i = 0; i < 5; ++i) 
    printf("%d\n", x[i]); 
} 

如果我gcc编译这个我得到一个编译错误:

foo.c:10: error: array subscript is not an integer 
3

标操作符在阵列而言是语法糖。当你具备以下条件:

class A {...}; 
A ar[17]; 
std::cout << ar[3] << std::endl; 

ar[3]没有比不同的说法:

*(ar + 3); 

所以ar[3.4]是等于说

*(ar + 3.4) (1) 

从C++标准5.7.1节 - 添加剂运营商我们读到:

(...) For addition, either both operands shall have arithmetic or unscoped enumeration type, or one operand shall be a pointer to a completely-defined object type and the other shall have integral or unscoped enumeration type.

这就是为什么表达式(1)导致compilation error

所以,当你索引通过浮法阵列你得到一个编译错误

相关问题