basic c/c++ question (const related)
-
I'd just like to make sure of something that I'm kind of worried about. This is not ok: char *Foo() { char ret[100] = "hello"; return ret; } This is not ok: char *Foo() { char ret[100] = "hello"; return ret; } This is ok: const char *Foo() { return "hello world"; } main() { printf(Foo()); } Is this right? Thanks!
-
I'd just like to make sure of something that I'm kind of worried about. This is not ok: char *Foo() { char ret[100] = "hello"; return ret; } This is not ok: char *Foo() { char ret[100] = "hello"; return ret; } This is ok: const char *Foo() { return "hello world"; } main() { printf(Foo()); } Is this right? Thanks!
return "hello world";
is fine because the string literal "hello world" is stored in the executable image, and stays allocated for the life of your program. --Mike-- http://home.inreach.com/mdunn/ "Holding the away team at bay with a non-functioning phaser was an act of unmitigated gall. I admire gall." -- Lt. Cmdr. Worf
-
I'd just like to make sure of something that I'm kind of worried about. This is not ok: char *Foo() { char ret[100] = "hello"; return ret; } This is not ok: char *Foo() { char ret[100] = "hello"; return ret; } This is ok: const char *Foo() { return "hello world"; } main() { printf(Foo()); } Is this right? Thanks!
When you say
char anArray[200]
you are saying "Grab me 200 characters worth of local space and call it "anArray". You could them go on to put "Hello World" into it if you wanted, but only by copying it in character by character, for example with:strcpy(anArray, "Hello World!");
However because the space for anArray is local it's discarded as soon as your function exits. A pointer returned to it will point to garbage, because that pointer looses it's validity when the routine exits. The string constant "Hello World" is a different kind of beasty. The string is stored by the compiler in static storage. It's address remains valid for the life of the program. When you say, for example,const char *p = "Hello World";
You are allocating a pointer. A memory location containing the address of that static string. Not a new block of memory containing the string itself (which is why it's ok to do a simple assignment in such a case rather than a more complex copy). Does that make things clearer?