如何为特定数量的字符串分配内存

How to allocate memory for specific number of strings?

本文关键字:字符串 分配 内存      更新时间:2023-10-16

我被赋予了编写字典之类的程序的任务,而我为含义分配内存的方式只是在构造函数中分配100个含义,这非常好。

然而,教授不同意这一点,他要求我重写代码,让我为相关的含义分配内存。我基本上不知道如何做到这一点,构造函数如何提前知道我会有多少含义?

你们有什么建议?我只发布了与问题相关的部分代码。

#include"expression.h"
//---------------------METHODS-------------------------------------------
Expression::Expression(int m_ctr)
{
    count_meanings = m_ctr; // Set the counter to 0
    meanings = new char * [100]; // Allocate memory for 100 meanings
}
Expression::~Expression()
{
    delete [] meanings; // Free the allocated memory
    delete [] word_with_several_meanings; // Free the allocated memory
}
void Expression::word(char *p2c)
{
    word_with_several_meanings = new char[strlen(p2c)+1];
    strcpy(word_with_several_meanings, p2c); // copy the string, method: DEEP copy
}
void Expression::add_meaning(char *p2c)
{
    meanings[count_meanings] = new char[strlen(p2c)+1];
    strcpy(meanings[count_meanings++], p2c); // copy the string, method: DEEP copy
}
char * Expression::get_word()
{
    return word_with_several_meanings;
}
char * Expression::get_meaning(int n_meaning)
{
    return * (meanings + n_meaning);
}
int Expression::get_total_number_of_meanings()
{
    return count_meanings;
}
int main(void)
{
    Expression expr;
    expr.word("bank");
    expr.add_meaning("a place to get money from");
    expr.add_meaning("a place to sit");
    cout << expr.get_word() << endl;
    for(int i = 0; i<expr.get_total_number_of_meanings(); i++)
        cout << " " << expr.get_meaning(i) << endl;

实现这一点的C++方法是使用:

  • std::string存储单个字符串(而不是原始字符*C类字符串)
  • std::vector存储字符串序列(如字典中的"含义")

因此,您可以在类中有一个vector<string>数据成员,并且可以使用vector::push_back()为其动态添加含义(即strings)。

如果出于某种原因想要保持原始C级别,可以使用链表数据结构,在每个节点内存储一个原始C字符串指针,当添加新含义时,可以创建一个指向该字符串的新节点,并将该节点添加到链表中。有这样一个节点定义的单链表可能就足够了:

struct MeaningListNode 
{
    char * Meaning;                 // Meaning raw C string
    struct MeaningListNode* Next;   // Pointer to next meaning node, or nullptr for last
};

但是,坦率地说,vector<string>>方法对我来说似乎更简单、更好。