Suppose an array int a[10]
.
Why we can't do a=a+1
? but the same is valid with a pointer variable.
int *ptr = a;
ptr = a+1;
How are both scenarios seen practically?
Suppose an array int a[10]
.
Why we can't do a=a+1
? but the same is valid with a pointer variable.
int *ptr = a;
ptr = a+1;
How are both scenarios seen practically?
Because array locations are constant.
You can't change the value of a
, since that represents the starting address of the array. Moving it doesn't make any sense.
With int *ptr;
your variable ptr
is just a single pointer and can of course be set to point to anywhere you like.
There's no contradiction here. It's a little like with functions, the name of a function evaluates to its address (called "a function pointer") but you can't assign to that either.
Because Array name is constant pointer pointing to its first element.You cannot change the value of constant variables,i,e what the const keyword is used for.
int a[10]; //here a (array variable is Const i,e you Cannot a=a+1)
int* const p=&a[0]; //here Also Same,Now p is Const i,e you Cannot p=p+1.
But Here:
int* pp=&a[0];//Here pp=pp+1 will work, Because pp is not Const.
You can if the array is a function argument
#include <stdio.h>
int rval(int a[10]) {
a = a + 1;
return a[0];
}
int main(){
int a[10] = {0,1,2,3,4,5,6,7,8,9};
printf ("%d\n", rval(a));
return 0;
}
Program output
1