字符指针数组

时间:2013-01-13 19:35:17

标签: c++ string pointers

我现在很困惑

这里有什么问题,我该怎么做才能解决问题

编辑: omg我很抱歉...我现在只是如此波动,以至于我甚至无法提出问题

我想将10个输入字符串分配给指针数组。

using namespace std;

int main(int argc, char *argv[])
{
    char *mess[10];
    int i = 0;

for (; i < 10; i++)
{                 
    cout << "Enter a string: ";   
    cin.getline(mess[i], 80);
}

for (i = 0; i < 10; i++)
    cout << mess[i];

system("PAUSE");
return EXIT_SUCCESS;
}

3 个答案:

答案 0 :(得分:3)

你想要的可能是这样声明你的数组:

char mess[10][80];

当您从getline阅读最多80个字符时。

您当前的实现构建了一个10 char*的数组,它们从未被初始化为指向已分配的缓冲区。

更安全的方法是使用std::string,因为将为您处理缓冲区大小。一个简单的改变:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
    std::string mess[10];
    int i = 0;

    for (; i < 10; i++)
    {                 
        cout << "Enter a string: ";   
        cin >> mess[i];
    }

    for (i = 0; i < 10; i++)
        cout << mess[i] << endl; // you probably want to add endl here

    system("PAUSE");
    return EXIT_SUCCESS;
}

应该给你你想要的东西。

修改

如果你绝对需要char *(这不是一个好主意),这就是你要找的东西:

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    char* mess[10];
    int i = 0;

    for (; i < 10; i++)
    {                 
        cout << "Enter a string: ";   
        mess[i] = new char[80]; // allocate the memory
        cin.getline(mess[i], 80);
    }

    for (i = 0; i < 10; i++)
    {
        cout << mess[i] << endl;
        delete[] mess[i]; // deallocate the memory
    }

    // After deleting the memory, you should NOT access the element as they won't be pointing to valid memory

    system("PAUSE");
    return EXIT_SUCCESS;
}

答案 1 :(得分:2)

你正在分配10个指针,但绝不会将它们初始化为指向getline可以读取输入的空间。

答案 2 :(得分:2)

您必须首先初始化您在此处声明的指针char *mess[10];以为它们分配内存。您可以使用new()表达式来分配请求的内存。

char *mess[10];
for (int k=0; k<10; k++)
{
    mess[k]=new char[80];
}

请记住,在使用new()函数分配内存后,必须始终释放完成数据后使用的内存。您可以 - 并始终 - 使用delete()表达式释放内存。

for (int j=0; j<10; j++)
{
   delete[] mess[j];
}

有关动态分配/取消分配内存的详细信息,请参阅here