-2

This code works fine when b is incremented and a is printed upon increment

#include<stdio.h>

int main()
{
int a[] = {10,20,30,40,50}, *p, j;
int *b = a;
for(j=0;j<5;j++)
{
printf("%d\n",*b);
b++;
}
return 0;
}

What happens here? What effect does a++ have here to suggest lvalue is required. Does a++ move to a point after all the elements of the array a?

#include<stdio.h>

int main()
{
int a[] = {10,20,30,40,50}, *p, j;
for(j=0;j<5;j++)
{
printf("%d\n",*a);
a++;
}
return 0;
}
Nobody
  • 397
  • 1
  • 5
  • 25
  • 6
    The fact that arrays decay to a pointers does not mean that they behave as pointers.... – LPs Jun 08 '17 at 12:43
  • 1
    Read this for the difference between a pointer and an array in C http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c – Fredrik Jun 08 '17 at 12:53
  • 2
    @LPs *The fact that arrays decay to a pointer ...* I prefer to think of the decay as "decays to *the address of the array*" instead of a pointer. The "address of the array" can't change, and can't be changed. – Andrew Henle Jun 08 '17 at 13:10
  • @AndrewHenle Yes, it is reasonable, maybe clearer. – LPs Jun 08 '17 at 13:13

1 Answers1

2

a is an array which decays into a (unmodifiable) pointer to the array (and only and always to the array) when used in pointer context. So it cannot be modified, so a++ doesn't work.

b is a pointer which can point everywhere and thus as well can be modified, so b++ works.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • It wouldn't be a stretch to say `a` is a `final` pointer, would it? – cs95 Jun 08 '17 at 12:51
  • 1
    @Shiva it would be a stretch. `a` is an array, and arrays can't be incremented. – Jens Gustedt Jun 08 '17 at 12:54
  • 1
    I wonder if in 100 years time there will still be people who think arrays are pointers – M.M Jun 08 '17 at 12:55
  • 1
    @Fredrik it's not an address, and the name designates the entire array, not the first element.It decays in any expression other than `sizeof` `_Alignof`, `++` `--`. – M.M Jun 08 '17 at 13:00
  • @Fredrik yes, variables are labels for memory locations... but `a` is a label for the location of the entire array (NOT for the address of that location, for just for the first element) – M.M Jun 08 '17 at 13:02
  • 1
    `sizeof x` is the same semantic for all types. If you think it is special for arrays that just shows you don't understand arrays. And yes there is a location for the whole array. Objects have a location. (That's what the "l" in "lvalue" stands for) – M.M Jun 08 '17 at 13:04
  • @M.M *it's not an address ...* It is "converted to an expression with type ‘‘pointer to *type* ’’ that points to the initial element of the array object and is not an lvalue." Which would be an address, no? It's quacking - it's a duck. – Andrew Henle Jun 08 '17 at 13:14
  • 1
    @AndrewHenle The result of the conversion is an address. The array is not an address. – M.M Jun 08 '17 at 13:16