How to easily destroy char arrays in C ++?

Sorry if this is allowed via Google - I didn't find anything.

char foo[4] = "abcd";

      

not valid in C ++ (due to the need for the '\ 0' terminator), but IIRC valid in C - is it correct?

I have a set of structs with many "fixed length" character fields that should be empty, not "\ 0" terminated. I would like to be able to do normal struct initialization - you know

mystruct bar = {17, "abcd", 0x18, "widget  ", ...

      

But I cannot do it in C ++. One solution, I think, would be to put all initialized structures like this in their own original C module (not ++). The ugly, time consuming solution I am trying to avoid is

mystruct bar = {17, {'a', 'b', 'c', 'd'}, 0x18, {'w', 'i', 'd', 'g', 'e', 't', ' ', ' '}, ...

      

Is there a good C ++ solution? A smart macro that effectively allows "abcd" to be char [4] without the '\ 0' terminator?

Thanks Charles

+3


source to share


3 answers


You can use a macro that will do the job:

#define MACRO_GET_1(str, i) \
    (sizeof(str) > (i) ? str[(i)] : 0)

#define MACRO_GET_4(str, i) \
    MACRO_GET_1(str, i+0),  \
    MACRO_GET_1(str, i+1),  \
    MACRO_GET_1(str, i+2),  \
    MACRO_GET_1(str, i+3)

#define MACRO_GET_STR(str) MACRO_GET_4(str, 0)

struct mystruct {
    char foo[4];
};

int main() {
    mystruct obj{ MACRO_GET_STR("abcd") };
    const char* str = "abcd";
    std::cout << memcmp(obj.foo, str, 4); // 0

    return 0;
}

      



This code is based on this solution and is easily extensible as well.

Anyway, there was a proposal a while back that probably never got to the standard. There are patches around that allow you to convert string literals to variable char packages.

0


source


Give the structure a constructor that takes char arrays of size 1 larger than you need, and ignore the trailing character when copying them.

bar::bar(int, char const(&)[5], int, char const(&)[9], ...)

      



Or you can just make the parameters char const*

and trust the user to pass the arrays of the desired size according to your documentation. If you don't want or can't add anything to the structure, then just create a function with the same arguments that returns one ( RVO should eliminate extra copying).

+1


source


I think it will work like a uint8 array (or whatever your compiler supports). Just never think of it as a string, because it isn't. It's much safer to allocate an extra char and initialize to zero (usually automatically). However, it is better to use STL components unless there is a compelling reason to do something else.

C ++ is not C. In C ++, the compiler tries to keep you safe. In C, this is entirely your own view.

0


source







All Articles