声明指向字符串的动态数组的问题

时间:2019-05-07 10:05:47

标签: c++ string

在网上进行练习时,遇到了一个我无法解决的问题。

用户必须输入一个数字(他将输入的句子数),然后继续逐个输入句子,这些句子将存储为字符串(顺便说一句,声明动态指针数组是必需的) 。但是,由于句子的数量不是先验可推导的,所以我知道指针数组的大小实际上就是句子的数量,但是我不知道如何声明一个动态的字符串指针数组< / em>。

使用我之前已经知道的东西,我想出了怎么做的方法,但是要使用字符数组而不是字符串数组。声明了一个指向chars动态数组的动态指针的行,如下所示:

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

据我所知,这将创建一个指针ptr,该指针指向动态的指针数组,该指针的元素每个都指向一个字符数组。我现在想做类似的事情,结果应该是ptr是一个指向动态指针数组的指针,该数组的每个元素都指向一个字符串。

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

2 个答案:

答案 0 :(得分:2)

您可以完全避免使用指针,而使用

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

std::array需要在编译时知道大小,然后在运行时学习。向量的工作方式类似于数组,但可以在运行时添加push_back个项目。

一旦知道,您就可以使用n声明一些字符串的指针:

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

,但是使用向量更容易。 每个pInput都是一个字符串,与std::vector版本一样。

答案 1 :(得分:2)

我认为您正在寻找的是类似的东西

std::size_t num;
std::cout << "enter the number of sentences\n";
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 sentence\n";
    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 sentences\n";
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 sentence\n";
    std::cin  >> sentences[i];
}
/* 
    ... (do something with the sentences, accessing them as sentences[i])
*/

std::size_t num;
std::cout << "enter the number of sentences\n";
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 sentence\n";
    std::cin  >> sentences[i];
}
/* 
    ... (do something with the sentences, accessing them as sentences[i])
*/

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