char * printstring(void)
{
return "my string";
}
Since what the function does is return a character array why do I have to state that my function returns char* and not char[] at the declaration.
Because because of the the way C was designed, arrays are not first-class citizens in it. You can neither return them nor pass them to a function by value.
If you want achieve either of those things, you'll have to wrap the array in a struct.
struct ten_chars{ char chars[10]; };
struct ten_chars printstring(void)
{
return (struct ten_chars){"my string"};
}
The string literal "my string" does have array type. Note that sizeof "my string" will evaluate to 10, as expected for an array that holds 10 chars (including the '\0'). You can think of "my string" as an identifier that identifies an array, and decays to a pointer to the first element of the array in most expressions (but not in, e.g., sizeof expressions).
So, in the return statement, "my string" decays to a pointer to the first element of the array that holds the characters of the string literal (and the null terminator). It is this pointer that is returned from the function, and this is why the return type must be char *.
For the record, it is not even possible to return an array from a function in C, though you can return a pointer to an array. You can also return a struct that contains an array field from a function.
Take a look at this example code:
#include <stdio.h>
char * getstring(void);
int main(void)
{
printf("%s\n", getstring());
return 0;
}
char * getstring(void)
{
printf("sizeof \"my string\": %zu\n", sizeof "my string");
printf("*(\"my string\" + 1): %c\n", *("my string" + 1));
return "my string";
}
Program output:
sizeof "my string": 10
*("my string" + 1): y
my string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With