c++ - How to allocate memory for specific number of strings? -


i given task program dictionary, , way allocating memory meanings allocate 100 meanings in constructor, works fine.

however, professor didn't approve , asked me rewrite code in way allocate memory relevant number of meanings. have no idea how that, how constructor know in advance how many meanings have?

what guys suggest? post part of code, relevant problem.

#include"expression.h"  //---------------------methods-------------------------------------------  expression::expression(int m_ctr) {     count_meanings = m_ctr; // set counter 0     meanings = new char * [100]; // allocate memory 100 meanings }  expression::~expression() {     delete [] meanings; // free allocated memory     delete [] word_with_several_meanings; // free allocated memory }  void expression::word(char *p2c) {     word_with_several_meanings = new char[strlen(p2c)+1];     strcpy(word_with_several_meanings, p2c); // copy string, method: deep copy }  void expression::add_meaning(char *p2c) {     meanings[count_meanings] = new char[strlen(p2c)+1];     strcpy(meanings[count_meanings++], p2c); // copy 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 money from");     expr.add_meaning("a place sit");      cout << expr.get_word() << endl;      for(int = 0; i<expr.get_total_number_of_meanings(); i++)         cout << " " << expr.get_meaning(i) << endl; 

the c++ way of doing use:

  • std::string store single string (instead of raw char* c-like strings)
  • std::vector store sequence of strings (like "meanings" in dictionary)

so, can have vector<string> data member inside class, , can dynamically add meanings (i.e. strings) it, using vector::push_back().

if - reason - want stay @ raw c level, use linked list data structure, storing raw c string pointer inside each node, , when add new meaning, can create new node pointing string, , add node linked list. singly-linked list having node definition may suffice:

struct meaninglistnode  {     char * meaning;                 // meaning raw c string     struct meaninglistnode* next;   // pointer next meaning node, or nullptr last }; 

but, frankly speaking, vector<string>> approach seems simpler , better me.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -