Stevie Stevie - 1 month ago 16
C Question

Function that returns an int value, instead of a string in C

I'm trying to write a function in C that gets an int as a parameter and returns a char array (or a string).

const char * month(int x)
{
char result[40];
if(x<=31) strcpy(result,"can be a day of the month");
else strcpy(result,"cannot be a day of the month");
return result;
}


But my function returns an int, not a string. I have read posts where people might have run into similar situations, but I can't understand how the pointer-type functions work and how to make them return what I want (I have documented a bit about pointers and I have an idea about how they work alone, but I have never tried to write a piece of code that adds some functionality to them, like making a solution more effective or something else.)

Answer

Considering this is a C code. (not sure if C++) Your best choice here is to have result declared outside the function scope and then pass a pointer inside the function that you are using that you can fill with your data (be sure to not overflow). In what you are using, result will be destroyed and you won't be able to use it.

void month(int x, char* result)
{
    if(x<=31) strcpy(result,"can be a day of the month");
    else strcpy(result,"cannot be a day of the month")
}

That was only a suggestion you could return instead some error code or whatever you want.