问题描述
字符串可以用作 C 中的数组索引吗?
Can a string be used as array index in C?
例如:字符串对应值一个"1二"2五"5十"10
Ex:String Corresponding value"ONE" 1"TWO" 2"FIVE" 5"TEN" 10
当上面列表中的字符串传递给函数时,函数必须返回上面指示的相应值.这可以通过声明一个以字符串为索引的常量数组来实现
When a string in the above list is passed to the function, the function must return the corresponding value indicated above. Can this be achieved by declaring a constant array with string as index
int *x;
x["ONE"] = 1;
x["TWO"] = 2;
x["FIVE"] = 5;
x["TEN"] = 5;
return x["string received by the function"];
上述逻辑没有按预期工作;是否有解决方法来实现上述逻辑以获得字符串索引数组?
The above logic does not work as expected; is there a workaround to implement the above logic in order to have a string-indexed array?
推荐答案
它可能会编译,但不会工作.
It might compile, but it won't work.
您要实现的目标并不完全清楚.我认为您需要一个关联数组,在这种情况下,您应该找到一个的库实现.
It's not entirely clear what you're trying to achieve. I think you want an associative array, in which case you should find a library implementation of one.
如果您正在寻找更像枚举类型的东西,您可以依靠C89,看看类似:>
If you're looking for something more like an enumerated type, and you can rely on C89, look at something like:
enum cardsuit {
CLUBS,
DIAMONDS,
HEARTS,
SPADES
};
如果你不能依赖 C89,那么你应该尝试一些 typedef
技巧.
If you can't rely on C89, then you should try some typedef
trickery.
这篇关于字符串可以用作数组索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!