Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the function have to return a char * but not a char array?

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.

like image 577
BareWithImANoob Avatar asked Oct 25 '25 16:10

BareWithImANoob


2 Answers

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"};
}
like image 200
PSkocik Avatar answered Oct 28 '25 05:10

PSkocik


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
like image 40
ad absurdum Avatar answered Oct 28 '25 07:10

ad absurdum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!