0

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.

4
  • manner is a pointer to const char, if you want the pointer to also be const pointer you need const char * const. Commented Jun 18, 2013 at 19:07
  • from the FAQ: stackoverflow.com/questions/890535/… Commented Jun 18, 2013 at 19:07
  • (not pretty sure)Strings in c are arrays with a reference at the first char .. at all initialisations you change the reference (pointer) to another .. Commented Jun 18, 2013 at 19:15
  • Yeah, that is exactly what happened, the pointer was to changed to already a pre initialized string ("World"). Commented Jun 18, 2013 at 19:20

2 Answers 2

6

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";
Sign up to request clarification or add additional context in comments.

2 Comments

oh... you beat me by 20 seconds.
Also, you should read this, very informative: stackoverflow.com/questions/16021454/…
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.