rubixibuc
rubixibuc

Reputation: 7397

Passing string literals to functions in C

When you assign a string literal such as "ABC" to char a[] ex.

char a[] = "ABC";

it has the effect of doing

char a[4] = {'A','B','C','0'};

does this same thing apply when you pass it to a function parameter

ex.

int f(char a[]);

vs.

int f(char *a);

Upvotes: 0

Views: 562

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126787

does this same thing apply when you pass it to a function parameter

No; in general, in C you can't pass arrays directly by value; every array parameter to a function is actually interpreted by the compiler as a pointer parameter, i.e. when you write

int f(char a[]);

the compiler sees

int f(char *a);

(the same applies even if you specify the dimensions of the array)


By the way,

it has the effect of doing

char a[3] = {'A','B','C"};

Actually, it has the effect of doing:

char a[4] = {'A','B','C', 0};

Upvotes: 5

Mankarse
Mankarse

Reputation: 40603

No, because both of those function declarations are identical. Both declare a function that takes a pointer to char, and in both cases the argument becomes initialised with a pointer to the first element of the string literal.

Upvotes: 2

Related Questions