我使用下面两行代码:
enum bus_sigs { REG0, REGA, REGB, REGC, REGD };
short bus[5];
目的是用枚举名称索引短裤数组。例如,我使用:bus[REGA]
。
我的行为很奇怪:如果我使用 bus[REGC]
,我会得到奇怪的值,就好像我正在从数组内存范围之外获取数据一样。如果我随后将第二行更新为:
short bus[10];
该行为再次符合预期。但这对我来说毫无意义。我只分配给 bus
数组中的 5 个成员。
我没有得到什么?
最佳答案
这很难说,因为您没有包含任何相关代码。但是,您可能会通过以下几种方式获得错误的值:
您使用了错误大小的指针并读取了数组末尾:
long* b = (long*)bus; result = b[4]; // this will read past the end of the array
您从其他位置复制到
bus
数组,但使用了错误的计数:short bus[5]; // this is 5 int count = sizeof(bus)/sizeof(bus[0]); // this will copy 5 bytes, instead of 5 shorts // (this is why bus[10] would fix the issue, for example) memcpy(bus, some_location, count);
您从不初始化数组,而是在写入之前读取值:
// this *doesn't* clear the contents of the array short bus[5]; // value of result is undefined result = bus[4];
关于c - 需要帮助理解枚举和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561493/