0

How does one simply make a mutator or setter for an array of strings? I have made a inspector or accessor but cant seem to figure out how to make a mutator.

much appreciated.

3
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by mike_2000_17
0
struct StringArray
{
   char sArray[10][10];
   void setString(char *s, int pos) {strcpy(sArray[pos], s);}
};

setString should change/set/mutate sArray by assigning s to element pos in sArray.

You need to use strcpy() to "assign" one C style string to another. You would need to be sure there is enough room in sArray[pos] to accomodate s in order to avoid a bug that might otherwise be difficult to spot.

You can change how you declare sArray.

0

Easy, you just return a reference from the indexing operator. Here's what I mean:

class int_array {
  private:
    int arr[10];
  public:
    // element accessor:
    int operator[](int i) const { return arr[i]; };
    // element mutator:
    int& operator[](int i) { return arr[i]; };
};

And that's it, same for std::string elements or anything else.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.