Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does function cause this compiler warning: Incompatible pointer to integer conversion returning 'char[20]' from a function...

Tags:

c

What is the problem in that function?

char printThis()
{
    char str[20] = "This is a string";
    return str;
}

I get a warning : Incompatible pointer to integer conversion returning 'char[20]' from a function with result type char

like image 998
jingo Avatar asked Mar 18 '26 19:03

jingo


1 Answers

Three problems that I can see:

  1. You are returning char* but the function is declared to return char. The latter is just a single character rather than a string.
  2. You are attempting to return memory that is only valid on the stack frame of the function. This is an error.
  3. Your function is declared so that it can receive any number of arguments. Better to explicitly declare it to receive none with void.

Fix like this:

char* printThis(void)
{
    char* str = strdup("This is a string");
    return str;
}

Here I am using strdup to allocate the string on the heap. If you really wanted a buffer that was 20 characters long then you would need to use malloc() followed by strcpy(). Either way the responsibility for freeing the returned string is passed onto the caller.

like image 90
David Heffernan Avatar answered Mar 21 '26 10:03

David Heffernan



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!