Search code examples
carrayspointersparameter-passingfunction-call

Are array names in function arguments treated differently than arrays declared locally (auto)


Please read the comments in the program below :

#include<stdio.h>
void test(char c[])
{
    c=c+2; //why does this work ?
    c--;
    printf("%c",*c);
}
int main()
{
    char ch[5]={'p','o','u','r'};
    //ch = ch+2;  //this is definitely not allowed on array names as they are not pointers
    test(ch);

    return 0;
}

OUTPUT
o

Solution

  • You should keep in mind that the name of the array "decays" to a pointer to its first element. This means that test(ch); is equivalent to test(&ch[0]);.

    Also, void test(char c[]) is nothing but void test(char* c), a pointer to a character. Pointers can be incremented or decremented which is why c = c + 2 and c-- compiles just fine.