Ad

Not Using '&' When Passing A Pointer

- 1 answer

"some_function" receives a pointer to a character - it's defined as follows:

void some_function(char *c);

From what I learned, when we want to call "some_function" - we should pass an to the argument using the '&' operator:

some_function(&some_char);

But I've seen working examples where "some_function" directly receives a string:

some_function("some string");

How does it work? Is this practice recommended?

Ad

Answer

In C all literal strings are really arrays of (read-only) characters, including the ending null-terminator.

And as all arrays in C, they can decay to a pointer to their first element.

Which means all string literals can be used whenever a char * is expected.


It's similar (but not equivalent) to having:

char some_string[] = "some string";
some_function(some_string);  // equal to some_string(&some_string[0])
Ad
source: stackoverflow.com
Ad