-3

"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?

shaiko
  • 159
  • 6

3 Answers3

1

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])
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Rather more like: `const char *some_string = "some string"; some_function(some_string);`. (in your code, `some_string` can be modified legally but isn't the case in OP's - string literal is directly passed). – P.P Jul 25 '20 at 10:45
0

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

Note that in the case of arrays, you should omit the & operator since an array decays to a pointer to its first element when passed as argument to a function.

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?

A string literal is basically stored in an not modifiable char array (likely but not necessary in read-only memory).

When you use a string literal like that which is is indicated by its surrounding "s, it decays to a pointer to its first element, which is of type char *.

So, There is no problem using this technique.

Note that you can't modify a string literal, so any attempt to change the contents of "some string" inside of `some_function invokes undefined behavior.

0

In C strings are actually an array of characters. String can be declared like this:

// # 1
char *some_string = "some string";
// # 2
char some_string[] = "some string";

and passed to function like this:

some_function(&some_string[0]);
some_function(some_string);
// or if it's just string literal
some_function("some string");

All of them have char * type.

Akmubi Lin
  • 59
  • 1
  • 7
  • I think you should at least mention how your definitions #1 and #2 differ. One is a pointer and the other allocates space for the contents. – rtoijala Jul 25 '20 at 11:14