提问者:小点点

指向字符数组的指针


我目前正在使用Koenig的加速C++学习C++,我在指向初始指针数组的指针方面遇到了一些麻烦。 书中说下面的代码


int main(int argc, char** argv)
{
    // if there are arguments, write them
    if (argc > 1) {
       int i; // declare i outside the for because we need it after the loop finishes
    for (i = 1; i < argc-1; ++i)
       // write all but the last entry and a space
      cout << argv[i] << " ";
     // argv[i] is a char*
      cout << argv[i] << endl;
    }
    return 0;
}

当使用“Hello,World”参数运行时,将生成Hello World,但是如果argv是指向指针数组的指针,那么argv[i]不应该是指向char数组的指针吗?


共3个答案

匿名用户

char*是“C字符串”--这是C语言中表示字符串的方式。 std::cout知道如何打印char*,因为<<<运算符随实现而重载。

C++还有std::string类型,这是表示字符串的另一种方式。

匿名用户

char**argvchar*argv[]相同

在C++中引用数组的变量只是指向它的第一个元素的指针。

argv基本上是一个C字符串数组,也就是字符数组。

argc告诉您argv指向的C字符串的数量。

您不需要知道C字符串(char[])有多长,因为它们是空终止的。 它只是从初始内存地址开始逐字符读取字符串,直到它到达空终止符。

匿名用户

您不能将argv用作数组,如果您想访问这个指针后面的数组,您应该取消对它的引用,并使用类似argv+i的内容。