Expression must be a modifiable lvalue

asked 2020-09-09T02:12:46.757+00:00
Shervan360 1,011 Reputation points

Hello,

The below code doesn't work.

# include <stdio.h>
int main()
{
    int arr[] = { 12,14,15,23,45 };

    for (size_t i = 0; i < 5; i++)
    {
        printf("%d\t",*arr);
        arr++;
    }

    return 0;
}

But the following code work.
I just saved arr in another variable.
Why the arr variable itself doesn't work?
We should be saved arr in another variable then we could use it.

# include <stdio.h>
int main()
{
    int arr[] = { 12,14,15,23,45 };
    int* a = arr;
    for (size_t i = 0; i < 5; i++)
    {

        printf("%d\t", *a);
        a++;
    }

    return 0;
}
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
2,615 questions
No comments
{count} votes

Accepted answer
  1. answered 2020-09-09T04:47:43.927+00:00
    WayneAKing 4,246 Reputation points

    arr++ is attempting to increment the array. You can't do that.
    The fact that the name of an array can be used like a pointer
    to access an array does not mean that the name of the array is
    a pointer. It "decays" - is translated into by the compiler - a
    pointer, in some contexts.

    You appear to be struggling with the concepts of arrays and pointers, as
    used in the C language (and inherited by C++). I strongly suggest that
    you spend as much time as needed to study the available tutorials and
    documentation on pointers and arrays, Otherwise you will be coming back
    to these forums repeatedly asking why your code doesn't work as expected.

    A TUTORIAL ON POINTERS AND ARRAYS IN C
    https://pdos.csail.mit.edu/6.828/2014/readings/pointers.pdf

    Relationship Between Arrays and Pointers
    https://www.programiz.com/c-programming/c-pointers-arrays

    6.8 — Pointers and arrays
    https://www.learncpp.com/cpp-tutorial/6-8-pointers-and-arrays/

    Exceptions to array decaying into a pointer?
    https://stackoverflow.com/questions/17752978/exceptions-to-array-decaying-into-a-pointer

    Pointer to an Array in C
    https://www.tutorialspoint.com/cprogramming/c_pointer_to_an_array.htm

    6. Arrays and Pointers
    http://c-faq.com/aryptr/index.html

    comp.lang.c FAQ list · Question 6.12
    http://c-faq.com/aryptr/aryvsadr.html

    comp.lang.c FAQ list · Question 6.13
    http://c-faq.com/aryptr/ptrtoarray.html

    • Wayne
    No comments

0 additional answers

Sort by: Most helpful