Home > Back-end >  Prober type for type "char text [100]" in class
Prober type for type "char text [100]" in class

Time:11-08

I have the following but I can't figure out what I am doing wrong. I obviously have the wrong types in the argument definition but I can't figure out what the correct syntax would be.

dto.h

...
class Dto
{
    public:
        struct msg
        {
            int id;
            byte type;
            char text[100];
        };

        char* getText();
        void setText(char* text);

    private:
        Dto::msg message;
...

dto.cpp

...
char* Dto::getText()
{
    return Dto::message.text;
}

void Dto::setText(char* text)
{
    Dto::message.text = text;
}
...

When I compile I get:

Dto.cpp:85:30: error: incompatible types in assignment of 'char*' to 'char [100]' Dto::message.text = text;

CodePudding user response:

You can't assign to an array. To copy a C-string to a char array, you need strcpy:

strcpy(Dto::message.text, text);

Better yet, use strncpy to ensure you don't overflow the buffer:

strncpy(Dto::message.text, text, sizeof(Dto::message.text));
Dto::message.text[sizeof(Dto::message.text)-1] = 0;

Note that you need to manually add a null byte at the end if the source string is too big, since strncpy won't null terminate in that case.

  • Related