In Borland C++ when I write this code, compiler gives this error --> "Lvalue required"
.
struct harf {
char word[10];
} pr[10];
void main() {
pr[0].word="Alireza"; //Lvalue required
getch();
}
What can I do?
In Borland C++ when I write this code, compiler gives this error --> "Lvalue required"
.
struct harf {
char word[10];
} pr[10];
void main() {
pr[0].word="Alireza"; //Lvalue required
getch();
}
What can I do?
Assignment operation is not allowed on arrays. C++ does not allow you to do that. For copying data to a character array, use string copy function. Use it like this.
strcpy(pr[0].word,"Alireza");
Another way to do this is to perform char by char copy using a loop yourself. Though better use library functions. :)
This question may also help you. Iterating through C-style array not using a pointer Remember that compound operations are not allowed on arrays in C++. You cannot directly perform arithmetic or logical operations on them.
You need to use strcpy(..) or strncpy(..). You can not directly assign it using assignment operator.
strcpy(pr[0].word,"Alireza");
Besides, since you are using C++, why not use std::string
. Something like:
std::string myString;
..
myString = "AlireZa";
use :
strncpy( pr[0].word, "Alireza", 10);
slightly safier solution is to :
strncpy( pr[0].word, "Alireza", sizeof(pr[0].word)/sizeof(pr[0].word[0]));
this way if word array changes you wont have to fix size change in other parts of your code. Using strncpy is considered safier than strcpy, because the second one can easily cause buffer overrun.
Still, its better to use std::string
pr[0].word
is an array. You cannot assign to arrays.
In your situation, the array expression decays to a pointer to the first element, but that expression is an rvalue (since obviously it makes no sense to attempt to change that pointer!).
pr[0].word
is an array at some location in memory.
"Alireza"
is another char array in some different location in memory.
Your assignment tries to redirect pr[0].word
to the Alireza memory, which is invalid since pr[0].word
is an array. You can redirect pointers but not arrays. You can either:
pr[0].word
a pointer and then set the pointer to different locations as you try to do now."Alireza"
memory to pr[0].word
memory, using strcpy
function as suggested by otherspr[0].word
as a std::string
which will do all memory-copy the magic for you under a convenient =
operator, making pr[0].word="Alireza"
valid again. This approach may also help you avoid some nasty bugs which could otherwise occur when dealing with "naked" char *
.