将动态的指针宣布为字符串的问题

Problem with declaring a dynamic array of pointers to strings

本文关键字:字符串 问题 动态 指针      更新时间:2023-10-16

在线执行练习作业时,我遇到了一个我无法解决的问题。

用户必须有一个数量(他将输入的句子数(,然后继续输入句子,将其存储为字符串(顺便说一句,宣布一系列动态的指针数组是强制性的(。但是,由于句子的数量不是先验的可推论,所以我知道指针数组的大小实际上是句子的数量,但是我不知道如何将一系列动态的指针声明为字符串。

使用我事先已经知道的东西,我想出了如何做相同的操作,但使用字符数组而不是字符串。将动态的指针宣布为动态的字符阵列的线看起来像这样:

char **ptr=new char*[n] {};

因此,在我的理解下,这会创建一个指针ptr,该指针指向一个动态的指针数组,每个点的元素都指向一个字符数组。我现在想做类似的事情,结果应该是 ptr是一个指向动态阵列的指针,每个点指向字符串的元素。

有人可以帮忙吗?我会感谢!

我认为您正在寻找的是

std::size_t num;
std::cout << "enter the number of sentencesn";
std::cin  >> num;
std::string *sentences = new std::string[num];
for(std::size_t i=0; i!=num; ++i) {
    std::cout << "enter the " << (i+1) << "th sentencen";
    std::cin  >> sentences[i];
}
/* 
    ... (do something with the sentences, accessing them as sentences[i])
*/
delete[] sentences;     // free the memory

请注意,这种编码样式是高度灰心的。问题是需要管理分配的内存:避免记忆泄漏和悬空指针(包括例外安全(。正确的方法是使用容器或智能指针。例如:

std::size_t num;
std::cout << "enter the number of sentencesn";
std::cin  >> num;
std::vector<std::string> sentences{num};
for(std::size_t i=0; i!=num; ++i) {
    std::cout << "enter the " << (i+1) << "th sentencen";
    std::cin  >> sentences[i];
}
/* 
    ... (do something with the sentences, accessing them as sentences[i])
*/

std::size_t num;
std::cout << "enter the number of sentencesn";
std::cin  >> num;
std::unique_ptr<std::string[]> sentences{new std::string[num]};
for(std::size_t i=0; i!=num; ++i) {
    std::cout << "enter the " << (i+1) << "th sentencen";
    std::cin  >> sentences[i];
}
/* 
    ... (do something with the sentences, accessing them as sentences[i])
*/

在两种情况下,您都不必担心调用delete:分配的内存将自动删除(即使发生异常(。

您可以完全避免使用

std::vector<std::string> input;

std::array需要在编译时知道大小,并且您在运行时学习了这一点。该向量的工作方式就像数组一样,但可以在运行时有 push_back ed。

您可以使用n声明指向一些字符串的指针:

std::string * pInputs = new std::string[n];

但是使用矢量更容易。每个pInput将是字符串,就像std::vector版本一样。