c - 需要帮助理解枚举和数组

标签 c arrays enums

我使用下面两行代码:

enum bus_sigs {  REG0, REGA, REGB, REGC, REGD };
short bus[5];

目的是用枚举名称索引短裤数组。例如,我使用:bus[REGA]

我的行为很奇怪:如果我使用 bus[REGC],我会得到奇怪的值,就好像我正在从数组内存范围之外获取数据一样。如果我随后将第二行更新为:

short bus[10];

该行为再次符合预期。但这对我来说毫无意义。我只分配给 bus 数组中的 5 个成员。

我没有得到什么?

最佳答案

这很难说,因为您没有包含任何相关代码。但是,您可能会通过以下几种方式获得错误的值:

  1. 您使用了错误大小的指针并读取了数组末尾:

    long* b = (long*)bus;
    result = b[4]; // this will read past the end of the array
    
  2. 您从其他位置复制到 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);
    
  3. 您从不初始化数组,而是在写入之前读取值:

    // 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/

相关文章:

javascript - 跨组件强制执行参数值限制

c - 凯撒密码程序的打印结果

c - ncurses透明控制台背景

c# - 如何使用 LINQ 过滤字符串 []?

javascript - AngularJs 通过数据绑定(bind)刷新将多个值从数组推送到另一个数组

Java - 删除 "Variable",保留有副作用的分配

c - C中结构的使用

hh :mm:ss. xxx 毫秒中的 C 程序时间戳和文件处理问题

python - 用python打乱一个数组,用python随机化数组项顺序

junit - 测试所有实现标记接口(interface)的枚举