1

I have a struct with a char array and a constructor that initializes the array with a defined String. I want to avoid the #define and instead pass a C++ string to the Constructor. But then again, the size of the char array is not known at compile time. What would be a good approach to this?

#define STRING_ "myString"

    struct myStruct {

        int nCode;
        char str1[sizeof(STRING_)];
        myStruct () 
        {
            nLangCode = 0x0409;
            strcpy(str1, STRING_ );
        }
    } ;
tzippy
  • 6,458
  • 30
  • 82
  • 151
  • 1
    When you do not know the size at compile time, you have to manually allocate storage once you know the size at runtime. – cli_hlt Feb 10 '14 at 11:12

3 Answers3

2

If you only know the size at runtime, there's no way to declare your member as an array, because variable length arrays aren't a C++ feature. Just use a std::string.

struct myStruct {

    int nCode;
    std::string str1;
    myStruct () : str1(STRING_)
    {
        nLangCode = 0x0409;
    }
} ;

This way you don't have to worry about copy constructors, assignment operators and destructors - which is what both other answers missed.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

You should use standard class std::string

For example

#include <string>
struct myStruct {

    int nLangCode;
    std::string str1;
    myStruct ( const char *s, int code ) : nLangCode( code ), str1( s )  
    {
    }
} ;

otherwise you need yourself dynamically allocate a character array using operator new. In this case you also have to define explicitly a copy constructor, destructor and the copy assignment operator.

In this case the constructor could look the following way

#include <cstring>

struct myStruct {

    int nLangCode;
    char *str;
    myStruct ( const char *s, int code ) : nLangCode( code )  
    {
        str = new char[std::strlen( s ) + 1];
        std::strcpy( str, s );
    }
    // Other special functions...
} ;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

If there's no need to hold a copy of the string and you don't need to modify the string, just don't use an array in the first place but just a raw pointer like char const * const str1; which you then initialize like str1( STRING_ ) in the constructor, like

#define _STRING "myString"

struct myStruct {
    const char * const str1;
    myStruct() : str1( _STRING ) { }
};

If you don't need a copy of the string but you do need to modify it, store it in an array directly and let the compiler figure out the correct size:

#define _STRING "myString"

struct myStruct {
    static char str1[];
    myStruct() {}
};

const myStruct::str1[] = _STRING;

If you do need a copy and you do need to modify the string, use a plain std::string as shown in the answer by Luchian Grigore.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207