#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?
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;
`}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With