tzippy
tzippy

Reputation: 6638

Initialize struct having a char array member with a string of dynamic length

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

Upvotes: 1

Views: 1160

Answers (3)

Frerich Raabe
Frerich Raabe

Reputation: 94299

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.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

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...
} ;

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

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.

Upvotes: 2

Related Questions