简体   繁体   English

带字符串的动态内存分配

[英]Dynamic Memory Allocation with Strings

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. 对于打印出名称的行,我不理解“ names [i]”如何打印出名称。 Shouldn't "names[i]" print out the pointers instead? “ names [i]”是否应该打印出指针? Any help on this is greatly appreciated. 在此方面的任何帮助将不胜感激。

There is an overload of operator<< with the following signature. 带有以下签名的operator<<重载。

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 . 您可以在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的成员函数重载带有签名:

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. 但是,在重载解析逻辑中,将以char const*作为参数类型的非成员函数赋予更高的优先级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM