0

Here in the 10th line I got an error saying expression must be a modifiable lvalue .

#include <stdio.h>

int main()
{
    int arr[3];
    for (int i = 0; i < 3; i++)
    {
        printf("Enter the value of element %d\n", (i + 1));
        scanf("%d", arr);
        arr++; // Error Here
    }

    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • `Can't we increase the address of an array arr[3] like this arr++?` No. – tkausl Jan 31 '22 at 14:42
  • That's normal, you can't modify the address of an array. You could write `scanf("%d", arr+i);` instead. – tevemadar Jan 31 '22 at 14:49
  • But if we create a pointer ptr and store arr in it and then increase ptr like ptr++ then the address of the array arr increases so why doesn't address of array arr increases in this case (arr++) since arr is the address of the first element of the array ? – Mohd Uzair Jan 31 '22 at 14:56
  • 1
    There's no "but". A pointer is a pointer, an array is an array. You can't "increment" an array, and that's it. – tevemadar Jan 31 '22 at 14:59
  • @MohdUzair You could create a pointer that points to the location in storage of the array, but you haven't created a magical link between your pointer and the array. If you increment the pointer you don't change the array and your pointer is just pointing at something different - it's unlikely that it's pointing at the next element of the array. – Steve Ives Feb 02 '22 at 08:38

1 Answers1

0

That doesn't make any sense. arr is an array so the concept of 'incrementing' it doesn't exist. You can increment a variable used as a pointer to the current element, but you're 99% of the way there already with i. Just prompt for a temporary value and then insert that into the array at location 'i':

for (int i = 0; i < 3; i++)
{
    printf("Enter the value of element %d\n", (i));
    scanf("%d", value); // Get new value
    arr[i] = value;     // store value in current element
}

(Sorry - my C is rusty but I hope you can see what I'm getting at).

I also changed your prompt to use i rather than i+1. c arrays start from 0 and 'i' has values from 0 to 2 which correlate to the element indices. You may not like arrays starting at 0, but they just do, because it's not the element 'number' but rather the 'offset' from the beginning of the array (this may help you understand why they start at 0).

It's confusing to ask for the value for element '1' (for example) when you are actually asking for a value for element 0.

Steve Ives
  • 7,894
  • 3
  • 24
  • 55