Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is not an error to increment array "a" in the below function?

#include<stdio.h>
void printd(char []);
int main(void){
       char a[100];
       a[0]='a';a[1]='b';a[2]='c';a[4]='d';
       printd(a);
       return 0;
}
void printd(char a[]){
        a++;
        printf("%c",*a);
        a++;
        printf("%c",*a);
}

Explanation: I was expecting that it would result in lvalue error. But it is working with out any error and giving bc as output. Why is this incrementing array "a" is not an error?

like image 532
Subhiksh Avatar asked Jul 18 '15 06:07

Subhiksh


1 Answers

If an array is passed to a function it decays to a pointer to the array's first element.

Due to this inside printd() the pointer a can be incremented and decremented, to point to different elements of the array a as defined in main().

Please note that when declaring/defining a function's parameter list for any type T the expression T[] is equivaltent to T*.

In question's specific case

void printd(char a[]);

is the same as

void printd(char * a);

The code below shows equivalent behaviour as the OP's code, with pa behaving like a in side printd():

#include <stdio.h>

int main(void)
{
   char a[100];
   a[0]='a';a[1]='b';a[2]='c';a[4]='d';

   {
     char * pa = a;

     pa++;
     printf("%c", *pa);
     pa++;
     printf("%c", *pa);
   }

   return 0;
`}
like image 121
alk Avatar answered Sep 22 '22 10:09

alk