0

I am currently studying C++ using Accelerated C++ by Koenig and i have a few troubles with the pointer to the initial array of pointers. It says in the book that the following code


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;
}

when ran with "Hello, world" arguments will produce Hello World but if argv is a pointer to an array of pointers then shouldn't argv[i] be a pointer to an array of char which output is a memory address instead of the array itself ?

V.Anh
  • 497
  • 3
  • 8
  • 15
  • 6
    Your understanding of pointer types is correct, but `char*` is a bit special, as it is almost always treated as a string. If this were some other kind of pointer, you would be right to expect the address to be printed out. – BoBTFish Jul 14 '20 at 14:50
  • 1
    Possibly relevant question: [cout << with char* argument prints string, not pointer value](https://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value) – Wyck Jul 14 '20 at 15:03

2 Answers2

4

A char* is a "C-string" -- it's how strings are represented in the C language. std::cout knows how to print char* because the << operator is overloaded with the implementation.

C++ also has the std::string type, which is another way to represent strings.

ATOMP
  • 1,311
  • 10
  • 29
0

char** argv is the same as char* argv[]

a variable referencing an array in c++ is just a pointer to it's first element.

argv basicly is an array of c-strings which are arrays of chars.

argc tells you the amount of c-strings argv points to.

you do not need to know how long the c-strings (char[]) are because they are null terminated. It's just going to read the string char by char starting at that initial memory adress until it reaches the null terminator.

Eric
  • 1,183
  • 6
  • 17
  • 1
    To be more precise, it is the same only when it appear as a function parameter, because array parameters decay to pointers. In general, `char**` and `char*[]` are different types. – Evg Jan 05 '22 at 11:12