-2
          int main()
           {
             int a[]={2,3,4,5,6};
             int j;
             for(j=0;j<5;j++)
               {
                    printf("%d\n",*a);
                      a++; 
               }
            return;
         }

gives Lvalue required error but

        int main()
        {
           int a[]={2,3,4,5,6};
           int *p,j;
            p=a;
          for(j=0;j<5;j++)
            {
              printf("%d\n",*p);
               p++; 
            }
          return;
        }

doesn't. why???? So I dont understant that even though in a[], a is treated as a pointer so why cant we increment it just like a pointer

  • 4
    "why?" - because the language specification says so. (And it probably does so because it doesn't quite make sense -- an array, contrary to your false belief, **is *NOT*** a pointer.) –  Nov 23 '13 at 10:57
  • 1
    Please don't repost the same question 30 minutes after the first post. – Avery Nov 23 '13 at 10:59

2 Answers2

2

Because array name is not a separate memory cell. It is a named memory extent. So it is not clear where to store the incremented value.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Pointers and arrays are not completely interchangeable.

int main ()
{
   int  var[MAX] = {10, 100, 200};

   for (int i = 0; i < MAX; i++)
   {
      *var = i;    // This is a correct syntax
      var++;       // This is incorrect.
   }
   return 0;
}

It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value. The reason for this is that var is a constant that points to the beginning of an array and can not be used as l-value.

Because an array name generates a pointer constant, it can still be used in pointer-style expressions, as long as it is not modified

Parag
  • 662
  • 9
  • 15