Assaf Malki
Assaf Malki

Reputation: 303

Returning a const string from a function in C

I have the following code:

const char * func_journey ()
{
    const char * manner = "Hello";

    manner = "World";

    return manner;

 }

 int main()
 {

     const char * Temp;

     Temp = func_journey();

     return 0;
 }

I ran it in debug just to see what happens, somehow manner changed from "Hello" to "World" and also the pointer changed even due I have declared it a const.

Another thing is that at the end of the run Temp was "World", now how can it be? manner was an automate variable inside func_journey, shouldn't it get destroyed at the end?

Thanks a lot.

Upvotes: 0

Views: 233

Answers (2)

user2435009
user2435009

Reputation: 11

The answer to your questions are two part: 1) you have declared pointer to a "const" and not a "const" pointer (which you wanted I guess). 2) The memory allocated for both "Hello" and "World" is not in function func_journey local stack but in a global read-only memory location (look into how string literals are allocated). If you declare using char array then "World" would not be copied back to Temp.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

I ran it in debug just to see what happens, somehow manner changed from "Hello" to "World"

That's precisely what your code told it to do, so there's no surprise that it did what you asked for.

and also the pointer changed even due I have declared it a const.

You declared it a pointer to const, not a const pointer (I know, this may sound confusing). When you write const char *, it means that what's pointed to is const. If you want to say that the pointer itself is const, you need

char * const manner = "Hello";

Upvotes: 6

Related Questions