0

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?

rjv
  • 6,058
  • 5
  • 27
  • 49
alisha
  • 39
  • 8

3 Answers3

2

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
-1

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.
Mysterious Jack
  • 621
  • 6
  • 18
  • 1
    "Array name is constant pointer" - no, it's an array. The fact that it can't change doesn't mean it's `const`. – The Paramagnetic Croissant Dec 10 '14 at 12:27
  • Internally it act like a constant, It has to be Because it should always represent the Base Address of its First Element.Am Pretty Sure About it. – Mysterious Jack Dec 10 '14 at 13:03
  • 1
    I see you are sure about it, but you're still wrong. All I am saying is that it's not a `const` pointer. A `const` pointer would look like `int *const p;`. An array is an array and is not a pointer. It can't be modified, but **not** because it's a `const`, rather because it's an array. Neither `const`s nor array can be modified, but **that does not mean that something which cannot be modified is a `const`.** – The Paramagnetic Croissant Dec 10 '14 at 13:07
-2

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
Weather Vane
  • 33,872
  • 7
  • 36
  • 56