-1
const char* colors[] = {"Red", "Blue", "Green"};
*ptr = new char[30];
memset(ptr,0,30);

I want to store colors(2-D) to ptr(1-D), something like this =>

ptr = "Red";
ptr+10 = "Blue";
ptr+20 = "Green";

this gives me lvalue required as left operand of assignment

Could someone guide me with this, please?

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550

1 Answers1

0

you request that :

strcpy(ptr, "red");
strcpy(ptr+10, "Blue");
strcpy(ptr+20, "Green");

after it is your responsibility to know where you placed the strings

Can be more practical/generic to have only one null char between each and at least two null char after the last ?

But frankly there are more practical/safe solutions using std::vector ...


About the error "lvalue required as left operand of assignment", you have it for the lines

ptr+10 = "Blue";
ptr+20 = "Green";

ptr+n is not a lvalue but a value, typically it is not a variable

bruno
  • 31,755
  • 7
  • 21
  • 36
  • 1
    please add some more explaination. Providing only the code is a good recipe to grow cargo cult programmers. Eg why does OPs code not work? – 463035818_is_not_a_number Jan 16 '19 at 14:36
  • Thanks!! it works!! I feel so silly asking this question :D Do you have any idea why I was getting that error with the way I was trying to do it? – Shubham Singla Jan 16 '19 at 14:36
  • @ShubhamSingla because you need to learn a little bit about C++ and built-in types and classes and... – Matthieu Brucher Jan 16 '19 at 14:42
  • 1
    ptr+10 = "Blue"; you're trying to assign a value to an object which is not an lvalue. You can still do something like *(ptr+10) = "Blue"; but this will not do what you want – Gojita Jan 16 '19 at 14:44
  • @ShubhamSingla I edited my answer, saying the same as some other guys including Gojita above – bruno Jan 16 '19 at 14:49
  • "is not a lvalue but a value" -> " is not a lvalue but a rvalue" ? – 463035818_is_not_a_number Jan 16 '19 at 15:05
  • @user463035818 no, if I am not wrong a _rvalue_ (renamed _prvalue_) can be assigned (https://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues) – bruno Jan 16 '19 at 15:41
  • but "value" is just the most general term that does not imply that you cannot assign to it, no? – 463035818_is_not_a_number Jan 16 '19 at 15:42
  • @user463035818 in my personal a value cannot. What is the right name for you ? – bruno Jan 16 '19 at 15:44
  • 1
    dont know, thats why I asked, my standardese is rather crappy, I always try to break things down to something simple that i can understand, which in this case is just "this wont work" but that doesnt qualify as an answer – 463035818_is_not_a_number Jan 16 '19 at 16:01