C++ array assign error: invalid array assignment

后端 未结 4 1125
无人及你
无人及你 2020-12-15 05:43

I\'m not a C++ programmer, so I need some help with arrays. I need to assign an array of chars to some structure, e.g.

struct myStructure {
  char message[40         


        
相关标签:
4条回答
  • 2020-12-15 06:01

    You need to use memcpy to copy arrays.

    0 讨论(0)
  • 2020-12-15 06:04

    The declaration char hello[4096]; assigns stack space for 4096 chars, indexed from 0 to 4095. Hence, hello[4096] is invalid.

    0 讨论(0)
  • 2020-12-15 06:11

    Why it doesn't work, if mStr.message and hello have the same data type?

    Because the standard says so. Arrays cannot be assigned, only initialized.

    0 讨论(0)
  • 2020-12-15 06:18

    Because you can't assign to arrays -- they're not modifiable l-values. Use strcpy:

    #include <string>
    
    struct myStructure
    {
        char message[4096];
    };
    
    int main()
    {
        std::string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'}
        myStructure mStr;
        strcpy(mStr.message, myStr.c_str());
        return 0;
    }
    

    And you're also writing off the end of your array, as Kedar already pointed out.

    0 讨论(0)
提交回复
热议问题