• C

Character Arrays In Functions

I'm having a problem when returning a character array from a function.

I've got:

char * function()
{
char myCharacter[] = "hello";

char *newPointer = newString;

return newPointer;
}

int main()
{
printf("%s", function());

return 0;
}

I get a strange answer.. I'm assuming something is wrong with my pointers and all.. could someone help.
cfansAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dimitryCommented:
char * function()
{
char myCharacter[] = "hello";  // <<<<< Means stack allocation that will be gone when you will leave the function...

char *newPointer = newString; // You meant newPointer = myCharater; ???

return newPointer;
}

Try:
char * function()
{
static char myCharacter[] = "hello";  // <<<<< Data Segment allocation

char *newPointer = myCharacter;

return newPointer;
}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
cfansAuthor Commented:
I don't quite understand why using "static" makes the difference, could you explain that for me?
PaulCaswellCommented:
Hi cfans,

dimitry is correct. A string, in C, is just a pointer to some memory. When you do:

char * function()
{
 char newString[] = "Hello";

Both the 'newString' pointer AND the "Hello" are placed on the stack (usually). When the function returns 'newString, it is actually returning a pointer to the area of the stack that had the "Hello" in it. Sadly, once 'function' exits, this memory becomes available for other functions to use ('printf' in this case) so, although at the moment you return from 'function' the string is valid and the pointer points to it, by the time printf gets to printing the string, it has been destroyed.

The easiest option, as dimitry has pointed out, is to make the string 'static'. This forces it out of the stack and into your data area and it therefore does not get destroyed. The downside of this is that EVERY time you call the function, the same address will be returned to the same memory. So if you do something like:

 char * str1 = function();
 char * str2 = function();
 strcpy(str2,"bye");
 printf("%s %s", str1, str2);

You will actually get "bye bye" printed because both str1 and str2 point to the same memory.

The common way to get around this is to use 'malloc'.

char * function ()
{
 char * newString = (char*)malloc(10);
 strcpy(newStr,"Hello");
 return newStr;
}

you could then do:

 char * str1 = function();
 char * str2 = function();
 strcpy(str2,"bye");
 printf("%s %s", str1, str2);

and you would get "hello bye" as you would expect.

There is one other method:

typedef struct ShortString
{
 char str[10];
} ShortString;

ShortString function ( void )
{
 ShortString s = {"Hello"};
 return s;
}

ShortString str1 = function();
ShortString str2 = function();

This is a little more complicated to understand but essentially, we are wrapping the string up in a structure so it can be returned by value and not as a pointer.

Paul
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.