24

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[4096];
};

string myStr = "hello"; // I need to create {'h', 'e', 'l', 'l', 'o'}

char hello[4096];
hello[4096] = 0;
memcpy(hello, myStr.c_str(), myStr.size());

myStructure mStr;
mStr.message = hello;

I get error: invalid array assignment

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

2
  • You have to use strcpy or memcpy function instead of mstr.message = hello. Commented Nov 7, 2010 at 17:18
  • The line hello[4096] = 0; is wrong. This is one past the last element of the array. Just remove this line. Commented Nov 7, 2010 at 17:27

4 Answers 4

30

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Actually, the arrays mStr.message and hello in Alex's code are lvalues, because the expressions &mStr.message and &hello are valid. (See section 5.3.1 paragraph 3 in the C++ standard.)
Yup, you're right -- sorry. It seems what I should have said was that myStr.message isn't a modifiable l-value.
Interesting. What's the motivation for this? I don't see an issue with assignment to arrays constituting copying the memory over.
@Claudiu My assumption would be it has to do with the fact that the array variable name itself in C refers to the pointer of the start address of the array and the type of the arrray does in principle not contain information about it's length. So a direct assignment would be a pointer assignment which you rarely want and an automatic array copy is not possible because the length is unkown from the type. With memcpy you have to specify the length.
15

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.

Comments

4

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

1 Comment

While this information is true, it does not answer the question that was asked. One could replace hello[4096] = 0; with hello[4095] = 0; without changing the essence of what is being asked.
4

You need to use memcpy to copy arrays.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.