Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*(a++) is giving error but not *(a+1)?? where a is array name?

Tags:

arrays

c

pointers

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.

like image 651
Dayal rai Avatar asked May 09 '13 06:05

Dayal rai


People also ask

What is the array name?

Array name is a type of name or a type of any element name that is share by all elements of an array but its indexes are different. Array name handle as a constant pointer, it can never change during execution of a program. Array name is also used to reach its all element.

Is array [] a pointer?

An array is a pointer, and you can store that pointer into any pointer variable of the correct type. For example, int A[10]; int* p = A; p[0] = 0; makes variable p point to the first member of array A.

Is array name a variable?

But an array name is not a variable; constructions like a=pa and a++ are illegal.

Why array name is a pointer?

An array name contains the address of first element of the array which acts like constant pointer. It means, the address stored in array name can't be changed. For example, if we have an array named val then val and &val[0] can be used interchangeably.


3 Answers

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

like image 120
MOHAMED Avatar answered Oct 25 '22 01:10

MOHAMED


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.

like image 27
Ahmed Masud Avatar answered Oct 25 '22 01:10

Ahmed Masud


'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));
}
like image 36
Shishir Gupta Avatar answered Oct 25 '22 00:10

Shishir Gupta