【发布时间】:2020-04-06 16:06:40
【问题描述】:
int main(int argc, const char** argv) {
std::cout << "Hello" << std::endl;
char arr2d[][4] = {"ABC", "DEF"};
for (char *i : arr2d)
{
std::cout << i << std::endl;
}
在这里,我将 forrange 的工作评估为:“对于arr2d 中的每个字符数组,将其打印到控制台”。这是有效的,所以,至少我的理解应该是正确的。上面代码sn-p的输出是,
muyustan@mint:~/Desktop/C_Files/oop$ g++ main.cpp -o main && ./main
Hello
ABC
DEF
正如预期的那样。
但是,如果我尝试这个,
int main(int argc, const char** argv) {
std::cout << "Hello" << std::endl;
char arr2d[][4] = {"ABC", "DEF"};
for (const char *i : argv)
{
std::cout << i << std::endl;
}
首先 IDE 会警告我,
这个基于范围的“for”语句需要一个合适的“begin”函数,但没有找到
如果我尝试编译,我会得到:
muyustan@mint:~/Desktop/C_Files/oop$ g++ main.cpp -o main && ./main
main.cpp: In function ‘int main(int, const char**)’:
main.cpp:30:26: error: ‘begin’ was not declared in this scope
for (const char *i : argv)
^~~~
main.cpp:30:26: note: suggested alternative:
In file included from /usr/include/c++/7/string:51:0,
from /usr/include/c++/7/bits/locale_classes.h:40,
from /usr/include/c++/7/bits/ios_base.h:41,
from /usr/include/c++/7/ios:42,
from /usr/include/c++/7/ostream:38,
from /usr/include/c++/7/iostream:39,
from main.cpp:1:
/usr/include/c++/7/bits/range_access.h:105:37: note: ‘std::begin’
template<typename _Tp> const _Tp* begin(const valarray<_Tp>&);
^~~~~
main.cpp:30:26: error: ‘end’ was not declared in this scope
for (const char *i : argv)
^~~~
main.cpp:30:26: note: suggested alternative:
In file included from /usr/include/c++/7/string:51:0,
from /usr/include/c++/7/bits/locale_classes.h:40,
from /usr/include/c++/7/bits/ios_base.h:41,
from /usr/include/c++/7/ios:42,
from /usr/include/c++/7/ostream:38,
from /usr/include/c++/7/iostream:39,
from main.cpp:1:
/usr/include/c++/7/bits/range_access.h:107:37: note: ‘std::end’
template<typename _Tp> const _Tp* end(const valarray<_Tp>&);
那么,为什么 argv 的行为与我的 arr2d[][4] 不同?不都是char指针(char数组还是字符串(?))的指针吗?
如果我的理解有问题,使用 forrange 打印 argv 的成分应该是什么结构?
【问题讨论】:
-
不,
argv是一个指向char的指针。arr2d是chars 的数组。 数组不是指针. -
@MilesBudnek 这是我被告知错误的事情,当时我在处理 C 时,在某个地方我读到“数组也是指针!”。
-
您听说这很可能与在某些情况下衰减为指针的数组有关(参见例如stackoverflow.com/questions/1461432/what-is-array-decaying),但是将它们视为等价是错误的,并且是代码中许多误解和错误的根源
-
那么你将如何定义一个指针数组呢?要使用范围循环检查 argv 的内容,请检查 this
-
还要注意 C 不是 C++。