By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 982 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

What, if anything, is wrong with the following code fragment?

P: n/a
Could anyone please help me. IS there something wrong with it?
char * function getString()

{

char myString[20];

sprintf(myString, "hello world");

return myString;

}
Jul 23 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
Chris wrote:
Could anyone please help me. IS there something wrong with it?
char * function getString()

{

char myString[20];

sprintf(myString, "hello world");

return myString;

}


Your function declaration is wrong. It must be

char *getString()

The function returns an adress of a local variable and your compiler
should have warned you already. The problem is, by the time you return
the adress it is already invalid. That is, the content of myString no
longer exists, yielding into some strange output if you try to print the
result of the function (arbitrary characters, if you are lucky they
might even make some sense ;) ).

--
Regards,

Karsten
Jul 23 '05 #2

P: n/a
"Chris" <ch***@hotmail.net> writes:
Could anyone please help me. IS there something wrong with it? Yes.
char * function getString()
{
char myString[20];
sprintf(myString, "hello world");
return myString;
}


myString is created within the routine but the 20 bytes of space it
uses is freed (because it's a local variable) when the function ends
and can be re-used for other reasons. The function returns a pointer
to the start of this space. You might initially find that "hello world"
is still there, but that's just luck.

http://www-h.eng.cam.ac.uk/help/tpl/...+/argsC++.html
is overkill, but might be of use.

Jul 23 '05 #3

P: n/a
In message <OF*******************@news-server.bigpond.net.au>, Chris
<ch***@hotmail.net> writes
Could anyone please help me. IS there something wrong with it?
char * function getString()

{

char myString[20];

sprintf(myString, "hello world");

return myString;

}

You're returning the address of a local variable. By the time
getString() returns, myString no longer exists.

--
Richard Herring
Jul 23 '05 #4

P: n/a
Chris wrote:
Could anyone please help me. IS there something wrong with it?


Yes, it involves the use of arrays and pointers by someone who doesn't
understand them. You should avoid them

std::string getString() {
return "hello world";
}
Jul 23 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.