7

In following code:

void main()
{
    char a[]={1,5,3,4,5,6};
    printf("%d\n",*(a++)); //line gives error: wrong type argument to increment
    printf("%d\n",*(a+1));
}

What is the difference between line 4 and line 5. I am not getting any error or warning with line 5.

Dayal rai
  • 6,548
  • 22
  • 29
  • 1
    I'm not good in C, but perhaps you can't double-increment (ie. `++` operator) arrays. – Voitcus May 09 '13 at 07:00
  • 9
    Completely off topic but `void main()` == bad! When you think `void main()`, picture someone smacking you with a stick. `int main()`, always! – Yuushi May 09 '13 at 07:01

3 Answers3

28

a is an array object and not a pointer so you could not use the operation a++ for an array object. because this is equivalent to :

a = a+ 1;

Here you are assigning to the array object a new value which is not allowed in C.

a + 1 return a pointer to the element 1 of your a array and it's allowed

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
4

Okay seriously bad coding practices: However let's first address your issue:

printf("%d\n",*(a++)); //this lines gives error: wrong type argument to increment

can't be used because a is an implicit reference to the array;

You CAN do this:

char b[]={1,5,3,4,5,6};
char *a = b;
printf("%d\n",*(a++)); //this lines will not give errors any more

and off you go...

Also *(a++) is NOT the same as *(a+1) because ++ attempts to modify operand whereas + simply add one to constant a value.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Ahmed Masud
  • 21,655
  • 3
  • 33
  • 58
  • Also `a++` evaluates to the old value of `a` and the stored value of `a` is incremented (postincrement) – Joe Aug 03 '13 at 13:09
3

'a' behaves like a const pointer. 'a' cannot change it's value or the address it is pointing to. This is because compiler has statically allocated memory of size of array and you are changing the address that it is referencing to.

You can do it as follows instead

void main()
{
char a[]={1,5,3,4,5,6};
char *ch;
ch=a;
printf("%d\n",*(ch++)); //this lines gives error no more
printf("%d\n",*(ch+1));
}
Shishir Gupta
  • 1,512
  • 2
  • 17
  • 32
  • 1
    @H2CO3 I said 'assume' `a` to be a const pointer. I didn't call it a const pointer. – Shishir Gupta Sep 22 '13 at 18:23
  • `a` is array reference and stores address of first member of array. I can safely 'assume' it to be a const pointer – Shishir Gupta Sep 22 '13 at 18:27
  • No, you can't. Also, an array is not a pointer. It's an array. It's not because it's a pointer that you can't assign to it. It's because it's prohibited to assign to an array. It doesn't have to be const. It's just not a modifiable lvalue. –  Sep 22 '13 at 18:29