0

I have a class containing few char* variables:

char* msgTopic     = "myHome/MSGS";
char* groupTopic   = "myHome/All";
char* errorTopic   = "myHome/Err";

but, I wish to have it defined outside the class and not hardcoded (update only prefixTopic outside the class,

char* prefixTopic  = "myHome";
char* msgTopic     = ""; // also tried-->  char* msgTopic = "AAAAAAAAAAA";
char* groupTopic   = "";
char* errorTopic   = "";

and then, down the code to have it defined as:

sprintf(msgTopic  ,"%s/Messages",prefixTopic);
sprintf(groupTopic,"%s/All",prefixTopic);
sprintf(errorTopic,"%s/Errors",prefixTopic);

BUT

both ways ( when defining variables as "", or just filled it up with chars to allocate space) caused topics to be defined with errors ( mostly - one variable contained both topics ).

Appreciated any help ( I don't think context of class is relevant )

guyd
  • 898
  • 1
  • 13
  • 39
  • 1
    Not a duplicate, but the answers to “[deprecated conversion from string constant to 'char*'](https://arduino.stackexchange.com/questions/13429)” should provide the answer you are looking for (and more). – Edgar Bonet Jul 12 '19 at 19:17

1 Answers1

2

First, you have to think about using dynamic or pre-allocated strings. Dynamic memory is not recommended for Arduino, so I will use pre-allocated strings.

In that case you need to think about the maximum length, I will take 32 for now:

#include <stdio.h>

class YourClass
{
  static const int MaxTopicLength = 32;

  char _msgTopic[MaxTopicLength];
  char _groupTopic[MaxTopicLength];
  char _errorTopic[MaxTopicLength];

  void FillStrings(const char* prefixTopic);
};

Than create in your class a function to fill the strings (untested):

void YourClass::FillStrings(const char* prefixTopic)
{
  snprintf(_msgTopic  , MaxTopicLength, "%s/Messages", prefixTopic);
  snprintf(_groupTopic, MaxTopicLength, "%s/All"     , prefixTopic);
  snprintf(_errorTopic, MaxTopicLength, "%s/Errors"  , prefixTopic);
}
Michel Keijzers
  • 12,759
  • 7
  • 37
  • 56