* (a ++) gives an error, but not * (a + 1) ?? where a is the name of the array?

In the 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 do not get any errors or warnings on line 5.

+7
source share
3 answers

a is an array object, not a pointer, so you cannot use the a++ operation for an array object. because it is equivalent to:

 a = a+ 1; 

Here you assign a new value to the array object that is not allowed in C.

a + 1 return a pointer to element 1 of your array a and it resolved

+26
source

Well offensive coding methods: let us solve the problem first:

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

cannot be used since a is an implicit array reference;

You can do it:

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

and you go ...

Also *(a++) does NOT match *(a+1) , because ++ trying to change the operand, while + just adds the value of the constant a .

+4
source

'a' behaves like a const pointer. "a" cannot change its value or the address it points to. This is because the compiler has statically allocated memory the size of the array, and you change the address to which it refers.

You can do it as follows

 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)); } 
+3
source

All Articles