1
#include <stdio.h>

void foo(char a[],char b[])
{
    a[0]='t';
    a[1]='e';
    a[2]='s';
    a[3]='t';
    a[4]='_';
    a[5]='a';
    a[6]=NULL;

    b[0]='t';
    b[1]='e';
    b[2]='s';
    b[3]='t';
    b[4]='_';
    b[5]='b';
    b[6]=NULL;

}

int main()
{
    char a[10],b[10];
    foo(a,b);
    printf("%s \n",a);    //outputs "test_a"
    printf("%s \n",b);    //outputs "test_b"
}

How does a[] and b[] char arrays in main() get its value, when foo() is neither using pointers nor returning any value when it is called through main()?

Correct me if I am wrong in saying "foo() is not using pointers".

1

1 Answer 1

4

Function foo() is actually using pointers, somehow. When arrays are passed to functions, it decays to the pointer to the first element of the array.

As it happens,

void foo(char a[],char b[])

and

void foo(char *a,char *b)

are perfectly interchangeable.

In your case, when called with parameters like foo(a,b);, from the function you can change the content of the memory area pointed by a and b. You don't need to return anything.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.