我有一个 string a
。 for循环中的条件 a[i]
for(int i = 0; a[i]; i++)
是什么意思?
原文由 dnguyen 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有一个 string a
。 for循环中的条件 a[i]
for(int i = 0; a[i]; i++)
是什么意思?
原文由 dnguyen 发布,翻译遵循 CC BY-SA 4.0 许可协议
for(int i = 0; a[i]; i++)
has the same meaning as for(int i = 0; a[i] != 0; i++)
, which means “enter the loop until the element a[i]
gets 0
; if a
是一个字符串,那么这意味着“进入循环直到 a[i]
指向字符串终止字符 \0
。
但是请注意,C++ 提供了其他迭代字符串字符的方法,例如, for (auto c : a) { cout << c << endl; }
原文由 Stephan Lechner 发布,翻译遵循 CC BY-SA 3.0 许可协议
4 回答2.9k 阅读✓ 已解决
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
在这种情况下“for(int i = 0; a[i]; i++)”,您的循环会一直执行,直到其中一个元素为空元素。当你看到这个表达式时,总是检查元素是否为空,以停止循环。
但是,该循环具有未定义的行为,因为如果索引 i 将达到最大数组的大小。您很可能会收到该类型的运行时错误:
超出范围数组大小或您试图访问内存的空空间时出错。
希望我的回答,适合你的问题。。