[英]C: Iterate through an array of strings
I'm currently learning C and am struggling with how to iterate through an array of strings. 我正在学习C,并且正在努力学习如何迭代字符串数组。
Let's just say I define an array, like so: 我们只是说我定义一个数组,如下所示:
char* argv_custom[] = {"--debug", "--verbose", "--test", "--ultimate"};
Now, how would I go about determining the number of strings within argv_custom? 现在,我将如何确定argv_custom中的字符串数量? (eg argc_custom)
(例如argc_custom)
Am I going the right way about this in the first place? 我是否正确地采取了正确的方式? Also, is it possible to do something like:
此外,是否可以做以下事情:
Pseudocode 伪代码
if ('--debug' in argv_custom) { // do stuff }
Now, how would I go about determining the number of strings within argv_custom?
现在,我将如何确定argv_custom中的字符串数量?
The canonical way : 规范方式 :
int argc_custom = sizeof(argv_custom) / sizeof(argv_custom[0]);
Note: This only works on the array itself, as soon as you have a pointer (such as if you pass argv_custom
to a function), it no longer works: 注意:这仅适用于数组本身,只要有指针(例如,如果将
argv_custom
传递给函数),它就不再起作用:
char **p = argv_custom;
int argc_custom = sizeof(p) / sizeof(p[0]); // No me gusta
is it possible to do something like: ...
是否可以做以下事情:......
There's no shortcut. 没有捷径。 You would have to iterate over each string, and do
strcmp
. 你必须迭代每个字符串,然后执行
strcmp
。 Of course, you could (and probably should) wrap this behaviour into a function. 当然,您可以(并且可能应该)将此行为包装到函数中。
you can do sizeof(argv_custom)/sizeof(argv_custom[0])
. 你可以做
sizeof(argv_custom)/sizeof(argv_custom[0])
。 This calculates the total length of the array divided by the size of every single element. 这将计算数组的总长度除以每个元素的大小。
I've had this question quite a few times and from what I've found my favorite solution is to just iterate through the pointer until null
. 我已经有过这个问题了很多次,从我发现我最喜欢的解决方案就是迭代指针直到
null
。 sizeof
stops working as soon as you start using functions and passing the arrays around. 一旦开始使用函数并传递数组,
sizeof
停止工作。
Here's a paradigm I've used time and time again in my assignments and it's been really helpful. 这是我在作业中一次又一次使用的范例,它真的很有帮助。 The exact same thing can be used for getting the length of a
cstring
or iterating through its characters. 完全相同的东西可用于获取
cstring
的长度或迭代其字符。
char* argv_custom[] = {"--debug", "--verbose", "--test", "--ultimate"};
char **temp = argv_custom;
int size = 0;
while (*temp) {
++size;
++temp;
}
This is not preferred over using sizeof
, however it's an alternative when you want to loop through it. 这
sizeof
使用sizeof
,但是当你想循环它时,它是另一种选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.