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 ?

2
  • 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. Commented Jul 14, 2020 at 14:50
  • 1
    Possibly relevant question: cout << with char* argument prints string, not pointer value Commented Jul 14, 2020 at 15:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.