Lvalue required error

后端 未结 3 830
花落未央
花落未央 2020-12-02 00:37

While working with pointers i wrote the following code,

int main()
{
    int a[]={10,20,30,40,50};
    int i;
    for(i=0;i<5;i++)
    {
        printf(\"         


        
相关标签:
3条回答
  • 2020-12-02 00:41

    Under most circumstances, the name of an array evaluates to a value that's suitable to assign to a pointer -- but it's still a value, not an actual pointer.

    This is analogous to a value like, say, 17. You can take the value 17, and assign it to an int. Once you do that, you can increment, decrement, and otherwise manipulate that int. You can't, however, do much of anything to 17 itself -- it is what it is, and can't be changed.

    The name of an array is pretty much the same way. It has the right type to be able to assign it to a pointer, but on its own it's just a value that you can't manipulate. If you assign that value to a pointer, you can manipulate the pointer, but you can never do much to the original value itself -- it is what it is, and can't be changed.

    0 讨论(0)
  • 2020-12-02 00:47

    You can't do a++ on a static array - which is not an Lvalue. You need to do on a pointer instead. Try this:

    int *ptr = a;
    int i;
    for(i=0;i<5;i++)
    {
        printf("\n%d",*ptr);
        ptr++;
    }
    

    Although in this case, it's probably better to just use the index:

    int i;
    for(i=0;i<5;i++)
    {
        printf("\n%d",a[i]);
    }
    
    0 讨论(0)
  • 2020-12-02 00:52

    http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Flvalue.htm

    also i guess it depends on the compiler?

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