我有一个包含 255 个元素的数组。我需要在此数组中存储 100 个值。例如,如果有 3 个项目 rose、red、rat 那么 arr[0]
应该代表 rose
,arr[1]
应该代表 red
和 arr[2]
作为 rat
。然后将这些值分配为 arr[0] = 100
、arr[1] = 200
、arr[2] = 300
。现在,当我想获取 rat
的值时,我应该能够通过访问其索引直接获取该值,即 arr[2]=300
。我的想法是创建宏并为每个项目赋值并直接访问数组中的值。
示例:
#define ROSE 0
#define RED 1
#define RAT 2
然后直接对于rat
我会说arr[RAT]
来获取值。对于 100 个项目,这是一个好方法吗?
添加:
现在,如果项目值的大小不同怎么办?对于前。 red
有 4 个字节的值,rat
有 2 个字节的值,然后对于 uint8 arr[255];
red
应该开始在 arr[1]
和 rat
应该从 arr[5]
开始。枚举在这里仍然有效吗?
最佳答案
您还可以使用 C Enumeration Declarations , 枚举
:
typedef enum {rose, red, rat} index;
现在在您的代码中您可以访问 arr[rat]
即 == arr[2]
。
一般来说,我避免为这种常量使用宏(其中许多常量的类型相似)。我认为它应该是一种具有用户定义域的类型,即 enum
。
An enumeration consists of a set of named integer constants. An enumeration type declaration gives the name of the (optional) enumeration tag and defines the set of named integer identifiers (called the "enumeration set," "enumerator constants," "enumerators," or "members").
我更喜欢数组大小的宏:
#define SIZE 100;
int arr[SIZE]
感谢@junix在我的回答中添加非常好的观点:
最好定义 enum
并添加最后一个元素以给出元素总数,例如:
typedef enum { rose,
red,
rat,
/* add new elements here */
item_count
} index;
现在我的枚举域范围是 [0, item_count]
,我们可以使用 item_count
值,例如:
int arr[item_count];
当然还有宏所没有的好处!
关于c - 访问数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17675353/