2

My professor is currently teaching the topic of Dynamic Memory Allocation along with pointers. I don't quite understand the following example:

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

int main(void)
{
    int i;
    char * names[7];        // declare array of pointers to char
    char temp[16];

    // read in 7 names and dynamically allocate storage for each
    for (i = 0; i < 7; i++)
    {
        cout << "Enter a name => ";
        cin >> temp;
        names[i] = new char[strlen(temp) + 1];

        // copy the name to the newly allocated address
        strcpy(names[i],temp);
    }

    // print out the names
    for (i = 0; i < 7; i ++) cout << names[i] << endl;

    // return the allocated memory for each name
    for (i = 0; i < 7; i++) delete [] names[i];

    return 0;
}

For the line that prints out the names, I don't understand how "names[i]" prints out the names. Shouldn't "names[i]" print out the pointers instead? Any help on this is greatly appreciated.

1
  • Don't use std::endl unless you need the extra stuff that it does. '\n' starts a new line. Commented Feb 1, 2016 at 14:49

1 Answer 1

5

There is an overload of operator<< with the following signature.

std::ostream& operator<<(std::ostream&, char const*);

which prints the null terminated string.

When you use

cout << names[i] << endl;

that overload is used.

You can see all the non-member overloads at http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2.

There is a member function overload of std::ostream with the signature:

std::ostream& operator<<( const void* value );

However, in the overload resolution logic, the non-member function with char const* as argument type is given higher priority.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.