0

I got this error when I used names to print the strings, but no errors when tempNames is used.

char* names[] = { "JIM",
                  "RAM",
                  "SAM",
                  0  };
int main(int argc, char *argv[])    
{
    char** tempNames = names ;        
    while(*names != 0)
        std::cout << *names++ << std::endl ; 
    return 0;
}

How come *names became an rvalue whereas *tempNames is an lvalue.

legends2k
  • 31,634
  • 25
  • 118
  • 222
Raju
  • 1,149
  • 1
  • 6
  • 19

1 Answers1

0

As Bill Lynch explains in the comments you're incrementing type char* [] that's not allowed. (It's easier if you think of it as type int [].) When you assign to a char** then you can increment it.

Or a better C++ iterator based solution C++11:

char* names[] = { "JIM",
                  "RAM",
                  "SAM" };


int main(int argc, char *argv[])
{

    char** tempNames = names ;

    for(auto i = std::begin(names); i != std::end(names); ++i){
        std::cout << *i << std::endl;
    } 

    return 0;
}
Community
  • 1
  • 1
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 1
    If you going to give a modern c++ variant, at least go all out: https://gist.github.com/sharth/10f767045f2fe335f95c – Bill Lynch Nov 30 '14 at 04:50
  • @BillLynch I agree that he should use `std::string` but I didn't want it to be unclear that he could do this with `char*`s or whatever. – Jonathan Mee Nov 30 '14 at 04:55
  • 1
    Thanks for the answer, but my question is differen, why *names++ is an rvalue, and *tempNames++ is an lvalue? – Raju Nov 30 '14 at 04:57
  • @Manesh Right if you use an iterator you'll find it will solve your problem. I'm honestly having a little trouble understanding why. I think it's the increment is confusing to the compiler somehow. Well and the iterator's just better syntax anyway, so there's that. – Jonathan Mee Nov 30 '14 at 05:01
  • 1
    @JonathanMee: Here's the reduced code: `int x[5]; x++;` which causes a compiler error: _cannot increment value of type 'int [5]'_ – Bill Lynch Nov 30 '14 at 05:03
  • @BillLynch Hmmm... I see what you're saying that compiler error is a bit misleading. I got the r-value error too. The real problem is that type `char* []` can't be moved. I'm getting around that by creating an iterator. You should add that as an answer, or I can edit mine. – Jonathan Mee Nov 30 '14 at 05:11
  • @BillLynch It's marked as duplicate now, which I think means that you can't add answers, so I just edited mine. – Jonathan Mee Nov 30 '14 at 05:18