Thread: Varible is different once returned.

  1. #1

    Varible is different once returned.

    Hey there,
    I have a varible which is declared inside the scope of a function, of the type const char*. If I printf() the varible it's correct value is displayed and then that varible is returned. If I then printf() the varible which was returned (from another function) the value is just scrambled characters. Could anyone suggest why this is happening?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    You can't return a pointer to a local variable and expect the memory to not be reclaimed when the function returns. In other words, this will not work because the memory for s is reclaimed when the function returns:
    #include <iostream>
    char *getStr()
      char s[100];
      std::cout<<"Enter a string: ";
      std::cin.getline ( s, sizeof s );
      return s;
    int main()
      std::cout<< getStr() <<std::endl;
    Last edited by Prelude; 01-03-2003 at 08:23 PM.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Dec 2002
    So, what you can do is return a string object or pass a char array buffer to the function where it is filled
    string func(void)
        string s = "special message";
        return s;
    // with this version, you must be sure that the buffer you pass to the
    // function is large enough to hold whatever is going to go in it...
    void funct(char *s)
        strcpy(s, "special message");
    If you speak or are learning Spanish, check out this Spanish and English Dictionary, it is a handy online resource.
    What happens is not as important as how you react to what happens. -Thaddeus Golas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What exactly is iterator returned by .end()?
    By pheres in forum C++ Programming
    Replies: 21
    Last Post: 12-09-2008, 09:50 AM
  2. Replies: 12
    Last Post: 10-16-2008, 02:49 PM
  3. Turning a varible into a global.
    By Queatrix in forum C++ Programming
    Replies: 2
    Last Post: 08-20-2005, 06:58 PM
  4. accessing varible in a c++ class
    By jccharl in forum C++ Programming
    Replies: 1
    Last Post: 03-10-2004, 03:01 PM
  5. Array Varible
    By Jonh in forum C++ Programming
    Replies: 4
    Last Post: 01-09-2003, 06:31 PM