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);


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 )


1 Answer 1


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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.