Home > Software design >  Isn't Array name a constant pointer, which can't be used in pointer arithmetic, so why doe
Isn't Array name a constant pointer, which can't be used in pointer arithmetic, so why doe

Time:10-29

The following C program gives me output as b but since Array name silently "decays" into a constant pointer so why does the following program work, It should have given an error saying l value required, ie. a variable pointer required for assignment on LHS?

void check(){
  char a[10]; 
  a[0] = 'a'; 
  a[1] = 'b'; 
  a[2] = 'c'; 
  f(a);
} 

void f(char a[]){
  a  ; 
  printf("%c",*a);
}

Edit :

Now I do the same thing but not in a different function, and I get the error following the updated code.

void check(){
  char a[10]; 
  a[0] = 'a'; 
  a[1] = 'b'; 
  a[2] = 'c'; 
 // f(a); 
  a  ; 
  printf("%c",*a);
}

source_file.c: In function ‘check’:
source_file.c:73:4: error: lvalue required as increment operand
   a  ;
    ^~

CodePudding user response:

In the code

void f(char a[]){
  a  ; 
  printf("%c",*a);
}

a is not an array - it's a pointer. In the context of a function parameter declaration, T a[N] and T a[] are "adjusted" to T *a - all three declare a as a pointer to T, not an array of T.

When you called f with an array argument:

f(a);

the expression a "decayed" from type "10-element array of int" to "pointer to int", so what f actually receives is a pointer, not an array object. It's exactly equivalent to writing

f( &a[0] );

In the code

void check(){
  char a[10]; 
  a[0] = 'a'; 
  a[1] = 'b'; 
  a[2] = 'c'; 
 // f(a); 
  a  ; 
  printf("%c",*a);
}

a is an array expression, not a pointer, and an expression of array type cannot be the operand of .

  • Related